iPhone Application Programming Guide
General2010-03-24
Intel and Intel Core are registered trademarks
Apple Inc.
of Intel Corportation or its subsidiaries in the
© 2010 Apple Inc.
United States and other countries.
All rights reserved.
Java and all Java-based trademarks are
trademarks or registered trademarks of Sun
No part of this publication may be reproduced,
Microsystems, Inc. in the U.S. and other
stored in a retrieval system, or transmitted, in
countries.
any form or by any means, mechanical,
electronic, photocopying, recording, or
OpenGL is a registered trademark of Silicon
otherwise, without prior written permission of
Graphics, Inc.
Apple Inc., with the following exceptions: Any
Simultaneously published in the United States
person is hereby authorized to store
and Canada.
documentation on a single computer for
Even though Apple has reviewed this document,personal use only and to print copies of
APPLE MAKES NO WARRANTY OR REPRESENTATION,documentation for personal use provided that
EITHER EXPRESS OR IMPLIED, WITH RESPECT TO
THIS DOCUMENT, ITS QUALITY, ACCURACY,the documentation contains Apple’s copyright
MERCHANTABILITY, OR FITNESS FOR A PARTICULARnotice.
PURPOSE. AS A RESULT, THIS DOCUMENT IS
PROVIDED “AS IS,” AND YOU, THE READER, AREThe Apple logo is a trademark of Apple Inc.
ASSUMING THE ENTIRE RISK AS TO ITS QUALITY
AND ACCURACY.Use of the “keyboard” Apple logo
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,(Option-Shift-K) for commercial purposes
INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES RESULTING FROM ANYwithout the prior written consent of Apple may
DEFECT OR INACCURACY IN THIS DOCUMENT, evenconstitute trademark infringement and unfair
if advised of the possibility of such damages.competition in violation of federal and state
THE WARRANTY AND REMEDIES SET FORTH ABOVElaws.
ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL
OR WRITTEN, EXPRESS OR IMPLIED. No AppleNo licenses, express or implied, are granted
dealer, agent, or employee is authorized to make
any modification, extension, or addition to thiswith respect to any of the technology described
warranty.in this document. Apple retains all intellectual
Some states do not allow the exclusion or limitationproperty rights associated with the technology
of implied warranties or liability for incidental ordescribed in this document. This document is
consequential damages, so the above limitation or
exclusion may not apply to you. This warranty givesintended to assist application developers to
you specific legal rights, and you may also havedevelop applications only for Apple-labeled
other rights which vary from state to state.computers.
Every effort has been made to ensure that the
information in this document is accurate. Apple
is not responsible for typographical errors.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010
App Store is a service mark of Apple Inc.
Apple, the Apple logo, Bonjour, Carbon, Cocoa,
Instruments, iPod, iPod touch, iTunes, Keychain,
Mac, Mac OS, Macintosh, Objective-C, Pages,
Quartz, Safari, Sand, Shake, Spaces, and Xcode
are trademarks of Apple Inc., registered in the
United States and other countries.
Cocoa Touch, Finder, iPhone, and Multi-Touch
are trademarks of Apple Inc.
NeXT is a trademark of NeXT Software, Inc.,
registered in the United States and other
countries.
Contents
IntroductionIntroduction 13Who Should Read This Document? 14
Prerequisites 14
Organization of This Document 14
Providing Feedback 15
See Also 15
Chapter 1The Core Application 17Core Application Architecture 17
The Application Life Cycle 17
The Event-Handling Cycle 20
Fundamental Design Patterns 22
The Application Runtime Environment 23
Fast Launch, Short Use 23
The Application Sandbox 23
The Virtual Memory System 24
The Automatic Sleep Timer 24
The Application Bundle 24
The Information Property List 26
Application Icon and Launch Images 28
Nib Files 29
Handling Critical Application Tasks 30
Initialization and Termination 30
Responding to Interruptions 30
Observing Low-Memory Warnings 32
Customizing Your Application’s Behavior 33
Launching in Landscape Mode 33
Communicating with Other Applications 34
Implementing Custom URL Schemes 35
Displaying Application Preferences 38
Turning Off Screen Locking 38
Internationalizing Your Application 39
Tuning for Performance and Responsiveness 41
Do Not Block the Main Thread 41
Using Memory Efficiently 41
Floating-Point Math Considerations 43
Reducing Power Consumption 43
Tuning Your Code 45
32010-03-24 | © 2010 Apple Inc. All Rights Reserved.
CONTENTSChapter 2Window and Views 47What Are Windows and Views? 47
The Role of UIWindow 47
The Role of UIView 48
UIKit View Classes 49
The Role of View Controllers 52
View Architecture and Geometry 52
The View Interaction Model 52
The View Rendering Architecture 54
View Coordinate Systems 57
The Relationship of the Frame, Bounds, and Center 58
Coordinate System Transformations 59
Content Modes and Scaling 60
Autoresizing Behaviors 62
Creating and Managing the View Hierarchy 63
Creating a View Object 65
Adding and Removing Subviews 65
Converting Coordinates in the View Hierarchy 67
Tagging Views 68
Modifying Views at Runtime 68
Animating Views 69
Responding to Layout Changes 71
Redrawing Your View’s Content 71
Hiding Views 72
Creating a Custom View 72
Initializing Your Custom View 72
Drawing Your View’s Content 73
Responding to Events 74
Cleaning Up After Your View 75
Chapter 3Event Handling 77Events and Event Types 77
Event Delivery 78
Responder Objects and the Responder Chain 78
Regulating Event Delivery 80
Touch Events 81
Events and Touches 81
Handling Multi-Touch Events 83
Motion Events 95
Event Handling Best Practices 96
Copy, Cut, and Paste Operations 97
UIKit Facilities for Copy-Paste Operations 97
Pasteboard Concepts 98
Selection and Menu Management 101
42010-03-24 | © 2010 Apple Inc. All Rights Reserved.
CONTENTSCopying and Cutting the Selection 102
Pasting the Selection 104
Dismissing the Editing Menu 105
Chapter 4Graphics and Drawing 107The UIKit Graphics System 107
The View Drawing Cycle 107
Coordinates and Coordinate Transforms 108
Graphics Contexts 109
Points Versus Pixels 109
Color and Color Spaces 110
Supported Image Formats 110
Drawing Tips 111
Deciding When to Use Custom Drawing Code 111
Improving Drawing Performance 111
Maintaining Image Quality 112
Drawing with Quartz and UIKit 112
Configuring the Graphics Context 113
Creating and Drawing Images 114
Creating and Drawing Paths 116
Creating Patterns, Gradients, and Shadings 116
Drawing with OpenGL ES 116
Applying Core Animation Effects 117
About Layers 117
About Animations 118
Chapter 5Text and Web 119About Text and Web Support 119
Text Views 119
Web View 121
Keyboards and Input Methods 122
Managing the Keyboard 124
Receiving Keyboard Notifications 124
Displaying the Keyboard 126
Dismissing the Keyboard 126
Moving Content That Is Located Under the Keyboard 127
Drawing Text 130
Displaying Content in a Web View 130
Chapter 6Files and Networking 133File and Data Management 133
Commonly Used Directories 133
Backup and Restore 134
52010-03-24 | © 2010 Apple Inc. All Rights Reserved.
CONTENTSFiles Saved During Application Updates 135
Keychain Data 135
Getting Paths to Application Directories 136
Reading and Writing File Data 137
File Access Guidelines 141
Saving State Information 141
Case Sensitivity 142
Networking 142
Tips for Efficient Networking 142
Using Wi-Fi 143
The Airplane Mode Alert 143
Chapter 7Multimedia Support 145Using Sound in iPhone OS 145
The Basics: Audio Codecs, Supported Audio Formats, and Audio Sessions 146
Playing Audio 150
Recording Audio 158
Parsing Streamed Audio 160
Audio Unit Support in iPhone OS 161
Best Practices for iPhone Audio 161
Using Video in iPhone OS 163
Recording and Editing Video 163
Playing Video Files 163
Chapter 8Device Support 167Setting Required Hardware Capabilities 167
Determining the Available Hardware Support 168
Communicating with External Accessories 169
Accessory Basics 170
Declaring the Protocols Your Application Supports 170
Connecting to an Accessory at Runtime 171
Monitoring Accessory-Related Events 172
Accessing Accelerometer Events 173
Choosing an Appropriate Update Interval 174
Isolating the Gravity Component from Acceleration Data 175
Isolating Instantaneous Motion from Acceleration Data 175
Getting the Current Device Orientation 176
Using Location and Heading Services 176
Getting the User’s Current Location 177
Getting Heading-Related Events 178
Displaying Maps and Annotations 180
Adding a Map View to Your User Interface 180
Displaying Annotations 182
Getting Placemark Information from the Reverse Geocoder 188
62010-03-24 | © 2010 Apple Inc. All Rights Reserved.
CONTENTSTaking Pictures with the Camera 188
Picking a Photo from the Photo Library 191
Using the Mail Composition Interface 191
Chapter 9Application Preferences 195Guidelines for Preferences 195
The Preferences Interface 196
The Settings Bundle 197
The Settings Page File Format 198
Hierarchical Preferences 199
Localized Resources 200
Adding and Modifying the Settings Bundle 200
Adding the Settings Bundle 200
Preparing the Settings Page for Editing 201
Configuring a Settings Page: A Tutorial 201
Creating Additional Settings Page Files 205
Accessing Your Preferences 205
Debugging Preferences for Simulated Applications 206
Document Revision History 20772010-03-24 | © 2010 Apple Inc. All Rights Reserved.
CONTENTS82010-03-24 | © 2010 Apple Inc. All Rights Reserved.
Figures, Tables, and Listings
Chapter 1The Core Application 17Figure 1-1
Application life cycle 18
Figure 1-2
The event and drawing cycle 20
Figure 1-3
Processing events in the main run loop 21
Figure 1-4
The Properties pane of a target’s Info window 27
Figure 1-5
The information property list editor 28
Figure 1-6
The flow of events during an interruption 31
Figure 1-7
Defining a custom URL scheme in the Info.plist file 36
Figure 1-8
The Language preference view 39
Table 1-1
Design patterns used by iPhone applications 22
Table 1-2
A typical application bundle 25
Table 1-3
Responsibilities of the application delegate
30
Table 1-4
Keys and values of the CFBundleURLTypes property 35
Table 1-5
Tips for reducing your application’s memory footprint 42
Table 1-6
Tips for allocating memory 43
Listing 1-1
The main function of an iPhone application 18
Listing 1-2
Handling a URL request based on a custom scheme 36
Listing 1-3
The contents of a language-localized subdirectory 40
Chapter 2Window and Views 47Figure 2-1
View class hierarchy 50
Figure 2-2
UIKit interactions with your view objects
53
Figure 2-3
View coordinate system 57
Figure 2-4
Relationship between a view's frame and bounds 58
Figure 2-5
Altering a view's bounds 59
Figure 2-6
View scaled using the scale-to-fill content mode
60
Figure 2-7
Content mode comparisons 61
Figure 2-8
View autoresizing mask constants 63
Figure 2-9
Layered views in the Clock application 64
Figure 2-10
View hierarchy for the Clock application 64
Figure 2-11
Converting values in a rotated view 68
Table 2-1
Autoresizing mask constants 62
Table 2-2
Animatable properties 69
Listing 2-1
Creating a window with views 66
Listing 2-2
Initializing a view subclass 73
Listing 2-3
A drawing method 74
Listing 2-4
Implementing the dealloc method 75
92010-03-24 | © 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGSChapter 3Event Handling 77Figure 3-1
The responder chain in iPhone OS 79
Figure 3-2
A multi-touch sequence and touch phases 82
Figure 3-3
Relationship of a UIEvent object and its UITouch objects 82
Figure 3-4
All touches for a given touch event 84
Figure 3-5
All touches belonging to a specific window 85
Figure 3-6
All touches belonging to a specific view 85
Figure 3-7
Pasteboard items and representations 100
Listing 3-1
Event-type and event-subtype constants 77
Listing 3-2
Detecting a double-tap gesture 86
Listing 3-3
Handling a single-tap gesture and a double-tap gesture 87
Listing 3-4
Tracking a swipe gesture in a view 88
Listing 3-5
Dragging a view using a single touch 89
Listing 3-6
Storing the beginning locations of multiple touches 90
Listing 3-7
Retrieving the initial locations of touch objects 90
Listing 3-8
Handling a complex multi-touch sequence 91
Listing 3-9
Determining when the last touch in a multi-touch sequence has ended 92
Listing 3-10
Calling hitTest: on a view’s CALayer object 92
Listing 3-11
Overriding hitTest:withEvent: 93
Listing 3-12
Forwarding touch events to “helper” responder objects 94
Listing 3-13
Becoming first responder 95
Listing 3-14
Handling a motion event 95
Listing 3-15
Displaying the editing menu 101
Listing 3-16
Conditionally enabling menu commands 102
Listing 3-17
Copying and cutting operations 103
Listing 3-18
Pasting data from the pasteboard to a selection 104
Chapter 4Graphics and Drawing 107Table 4-1
Supported image formats 110
Table 4-2
Tips for improving drawing performance 111
Table 4-3
Core graphics functions for modifying graphics state 113
Table 4-4
Usage scenarios for images 115
Chapter 5Text and Web 119Figure 5-1
Text classes in the UICatalog application 120
Figure 5-2
A web view 122
Figure 5-3
Several different keyboard types 123
Figure 5-4
Several different keyboards and input methods 124
Figure 5-5
Relative keyboard sizes in portrait and landscape modes 125
Figure 5-6
Adjusting content to accommodate the keyboard 127
Listing 5-1
Handling the keyboard notifications 128
Listing 5-2
Additional methods for tracking the active text field. 129
102010-03-24 | © 2010 Apple Inc. All Rights Reserved.
Document Outline
- iPhone Application Programming Guide
- Contents
- Figures, Tables, and Listings
- Introduction
- The Core Application
- Core Application Architecture
- The Application Life Cycle
- The Main Function
- The Application Delegate
- The Main Nib File
- The Event-Handling Cycle
- Fundamental Design Patterns
- The Application Runtime Environment
- Fast Launch, Short Use
- The Application Sandbox
- The Virtual Memory System
- The Automatic Sleep Timer
- The Application Bundle
- The Information Property List
- Application Icon and Launch Images
- Nib Files
- Handling Critical Application Tasks
- Initialization and Termination
- Responding to Interruptions
- Observing Low-Memory Warnings
- Customizing Your Applications Behavior
- Launching in Landscape Mode
- Communicating with Other Applications
- Implementing Custom URL Schemes
- Registering Custom URL Schemes
- Handling URL Requests
- Displaying Application Preferences
- Turning Off Screen Locking
- Internationalizing Your Application
- Tuning for Performance and Responsiveness
- Do Not Block the Main Thread
- Using Memory Efficiently
- Reducing Your Applications Memory Footprint
- Allocating Memory Wisely
- Floating-Point Math Considerations
- Reducing Power Consumption
- Tuning Your Code
- Window and Views
- What Are Windows and Views?
- The Role of UIWindow
- The Role of UIView
- UIKit View Classes
- The Role of View Controllers
- View Architecture and Geometry
- The View Interaction Model
- The View Rendering Architecture
- Core Animation Basics
- Changing the Layer of a View
- Animation Support
- View Coordinate Systems
- The Relationship of the Frame, Bounds, and Center
- Coordinate System Transformations
- Content Modes and Scaling
- Autoresizing Behaviors
- Creating and Managing the View Hierarchy
- Creating a View Object
- Adding and Removing Subviews
- Converting Coordinates in the View Hierarchy
- Tagging Views
- Modifying Views at Runtime
- Animating Views
- Configuring Animation Parameters
- Configuring an Animation Delegate
- Responding to Layout Changes
- Redrawing Your Views Content
- Hiding Views
- Creating a Custom View
- Initializing Your Custom View
- Drawing Your Views Content
- Responding to Events
- Cleaning Up After Your View
- Event Handling
- Events and Event Types
- Event Delivery
- Responder Objects and the Responder Chain
- Regulating Event Delivery
- Touch Events
- Events and Touches
- Handling Multi-Touch Events
- The Event-Handling Methods
- Basics of Touch-Event Handling
- Handling Tap Gestures
- Handling Swipe and Drag Gestures
- Handling a Complex Multi-Touch Sequence
- Hit-Testing
- Forwarding Touch Events
- Handling Events in Subclasses of UIKit Views and Controls
- Motion Events
- Event Handling Best Practices
- Copy, Cut, and Paste Operations
- UIKit Facilities for Copy-Paste Operations
- Pasteboard Concepts
- Named Pasteboards
- Pasteboard Persistence
- Pasteboard Owner and Items
- Representations and UTIs
- Change Count
- Selection and Menu Management
- Copying and Cutting the Selection
- Pasting the Selection
- Dismissing the Editing Menu
- Graphics and Drawing
- The UIKit Graphics System
- The View Drawing Cycle
- Coordinates and Coordinate Transforms
- Graphics Contexts
- Points Versus Pixels
- Color and Color Spaces
- Supported Image Formats
- Drawing Tips
- Deciding When to Use Custom Drawing Code
- Improving Drawing Performance
- Maintaining Image Quality
- Drawing with Quartz and UIKit
- Configuring the Graphics Context
- Creating and Drawing Images
- Creating and Drawing Paths
- Creating Patterns, Gradients, and Shadings
- Drawing with OpenGL ES
- Applying Core Animation Effects
- About Layers
- About Animations
- Text and Web
- About Text and Web Support
- Text Views
- Web View
- Keyboards and Input Methods
- Managing the Keyboard
- Receiving Keyboard Notifications
- Displaying the Keyboard
- Dismissing the Keyboard
- Moving Content That Is Located Under the Keyboard
- Drawing Text
- Displaying Content in a Web View
- Files and Networking
- File and Data Management
- Commonly Used Directories
- Backup and Restore
- Files Saved During Application Updates
- Keychain Data
- Getting Paths to Application Directories
- Reading and Writing File Data
- Reading and Writing Property List Data
- Using Archivers to Read and Write Data
- Writing Data to Your Documents Directory
- Reading Data from the Documents Directory
- File Access Guidelines
- Saving State Information
- Case Sensitivity
- Networking
- Tips for Efficient Networking
- Using Wi-Fi
- The Airplane Mode Alert
- Multimedia Support
- Using Sound in iPhone OS
- The Basics: Audio Codecs, Supported Audio Formats, and Audio Sessions
- iPhone Hardware and Software Audio Codecs
- Audio Sessions
- Playing Audio
- Playing Media Items with iPod Library Access
- Playing UI Sound Effects or Invoking Vibration Using System Sound Services
- Playing Sounds Easily with the AVAudioPlayer Class
- Playing Sounds with Control Using Audio Queue Services
- Creating an Audio Queue Object
- Controlling the Playback Level
- Indicating Playback Level
- Playing Multiple Sounds Simultaneously
- Playing Sounds with Positioning Using OpenAL
- Recording Audio
- Recording with the AVAudioRecorder Class
- Recording with Audio Queue Services
- Parsing Streamed Audio
- Audio Unit Support in iPhone OS
- Best Practices for iPhone Audio
- Tips for Using Audio
- Preferred Audio Formats in iPhone OS
- Using Video in iPhone OS
- Recording and Editing Video
- Playing Video Files
- Device Support
- Setting Required Hardware Capabilities
- Determining the Available Hardware Support
- Communicating with External Accessories
- Accessory Basics
- Declaring the Protocols Your Application Supports
- Connecting to an Accessory at Runtime
- Monitoring Accessory-Related Events
- Accessing Accelerometer Events
- Choosing an Appropriate Update Interval
- Isolating the Gravity Component from Acceleration Data
- Isolating Instantaneous Motion from Acceleration Data
- Getting the Current Device Orientation
- Using Location and Heading Services
- Getting the Users Current Location
- Getting Heading-Related Events
- Displaying Maps and Annotations
- Adding a Map View to Your User Interface
- Zooming and Panning the Map Content
- Displaying the Users Current Location
- Converting Between Coordinates and Pixels
- Displaying Annotations
- Adding and Removing Annotation Objects
- Defining Annotation Views
- Creating Annotation Views
- Handling Events in an Annotation View
- Getting Placemark Information from the Reverse Geocoder
- Taking Pictures with the Camera
- Picking a Photo from the Photo Library
- Using the Mail Composition Interface
- Application Preferences
- Guidelines for Preferences
- The Preferences Interface
- The Settings Bundle
- The Settings Page File Format
- Hierarchical Preferences
- Localized Resources
- Adding and Modifying the Settings Bundle
- Adding the Settings Bundle
- Preparing the Settings Page for Editing
- Configuring a Settings Page: A Tutorial
- Creating Additional Settings Page Files
- Accessing Your Preferences
- Debugging Preferences for Simulated Applications
- Revision History
Add New Comment