UIApplicationDelegate Protocol Reference

Conforms to
Framework
/System/Library/Frameworks/UIKit.framework
Availability
Available in iOS 2.0 and later.
Declared in
UIApplication.h
Companion guides
Related sample code

Overview

The UIApplicationDelegate protocol declares methods that are implemented by the delegate of the singleton UIApplication object. These methods provide you with information about key events in an app’s execution such as when it finished launching, when it is about to be terminated, when memory is low, and when important changes occur. Implementing these methods gives you a chance to respond to these system events and respond appropriately.

One of the main jobs of the app delegate is to track the state transitions the app goes through while it is running. Apps can be in the not running, inactive, active, background or suspended state. Transitions between these states often require a response from your app to ensure that it is doing the right thing. For example, a background app would need to stop updating its user interface. You provide the response to these transitions using the methods of the app delegate.

Launch time is also a particularly important point in an app’s life cycle. In addition to the user launching an app by tapping its icon, an app can be launched in order to respond to a specific type of event. For example, it could be launched in response to an incoming push notification, it could be asked to open a file, or it could be launched to handle some background event that it had requested. In all of these cases, the options dictionary passed to the application:didFinishLaunchingWithOptions: method provides information about the reason for the launch.

In situations where the app is already running, the methods of the app delegate are called in response to key changes. Although the methods of this protocol are optional, most or all of them should be implemented.

In iOS 6 and later, the app delegate also plays an important role in restoring and preserving the state of your app. The delegate tells UIKit whether state restoration and preservation should proceed at all. It may also provide view controller objects in some cases, acting as the last chance for your app to provide a view controller object during restoration.

For more information about the launch cycle of an app and how you manage state transitions using the methods of the app delegate, see iOS App Programming Guide. For more information about the UIApplication singleton class, see UIApplication Class Reference.

Tasks

Monitoring App State Changes

Providing a Window for Storyboarding

Managing the Default Interface Orientations

Downloading Data in the Background

Handling Remote Notifications

Handling Local Notifications

Responding to System Notifications

Managing App State Restoration

Opening a URL Resource

Managing Status Bar Changes

Responding to Content Protection Changes

Properties

window

The window to use when presenting a storyboard.

@property(nonatomic, retain) UIWindow *window
Discussion

This property contains the window used to present the app’s visual content on the device’s main screen.

Implementation of this property is required if your app’s Info.plist file contains the UIMainStoryboardFile key. Fortunately, the Xcode project templates usually include a synthesized declaration of the property automatically for the app delegate. The default value of this synthesized property is nil, which causes the app to create a generic UIWindow object and assign it to the property. If you want to provide a custom window for your app, you must implement the getter method of this property and use it to create and return your custom window.

For more information about the “UIMainStoryboardFile” in Information Property List Key Reference key, see Information Property List Key Reference.

Availability
  • Available in iOS 5.0 and later.
Related Sample Code
Declared In
UIApplication.h

Instance Methods

application:didChangeStatusBarFrame:

Tells the delegate when the frame of the status bar has changed.

- (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame
Parameters
application

The singleton app object.

oldStatusBarFrame

The previous frame of the status bar, in screen coordinates.

Discussion

After calling this method, the app also posts a UIApplicationDidChangeStatusBarFrameNotification notification to give interested objects a chance to respond to the change.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

application:didChangeStatusBarOrientation:

Tells the delegate when the interface orientation of the status bar has changed.

- (void)application:(UIApplication *)application didChangeStatusBarOrientation:(UIInterfaceOrientation)oldStatusBarOrientation
Parameters
application

The singleton app object.

oldStatusBarOrientation

A constant that indicates the previous orientation of the app’s user interface; see “Monitoring App State Changes” for details.

Discussion

The delegate can get the current device orientation from the shared UIDevice object.

After calling this method, the app also posts a UIApplicationDidChangeStatusBarOrientationNotification notification to give interested objects a chance to respond to the change.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

application:didDecodeRestorableStateWithCoder:

Tells your delegate to restore any high-level state information as part of the state restoration process.

- (void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder
Parameters
application

The singleton app object.

coder

The keyed archiver containing the app’s previously saved state information.

Discussion

The state restoration system calls this method as the final step in the state restoration process. By the time this method is called, all other restorable objects will have been restored and put back into their previous state. You can use this method to read any high-level app data you saved in the application:willEncodeRestorableStateWithCoder: method and apply it to your app.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

application:didFailToRegisterForRemoteNotificationsWithError:

Sent to the delegate when Apple Push Service cannot successfully complete the registration process.

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
Parameters
application

The app object that initiated the remote-notification registration process.

error

An NSError object that encapsulates information why registration did not succeed. The app can choose to display this information to the user.

Discussion

The delegate receives this message after the registerForRemoteNotificationTypes: method of UIApplication is invoked and there is an error in the registration process.

For more information about how to implement push notifications in your app, see Local and Push Notification Programming Guide.

Availability
  • Available in iOS 3.0 and later.
Declared In
UIApplication.h

application:didFinishLaunchingWithOptions:

Tells the delegate that the launch process is almost done and the app is almost ready to run.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Parameters
application

The singleton app object.

launchOptions

A dictionary indicating the reason the app was launched (if any). The contents of this dictionary may be empty in situations where the user launched the app directly. For information about the possible keys in this dictionary and how to handle them, see “Launch Options Keys.”

Return Value

NO if the app cannot handle the URL resource, otherwise return YES. The return value is ignored if the app is launched as a result of a remote notification.

Discussion

You should use this method (and the corresponding application:willFinishLaunchingWithOptions: method) to complete your app’s initialization and make any final tweaks. This method is called after state restoration has occurred but before your app’s window and other UI have been presented. At some point after this method returns, the system calls another of your app delegate’s methods to move the app to the active (foreground) state or the background state.

This method represents your last chance to process any keys in the launchOptions dictionary. If you did not evaluate the keys in your application:willFinishLaunchingWithOptions: method, you should look at them in this method and provide an appropriate response.

Objects that are not the app delegate can access the same launchOptions dictionary values by observing the notification named UIApplicationDidFinishLaunchingNotification and accessing the notification’s userInfo dictionary. That notification is sent shortly after this method returns.

The return result from this method is combined with the return result from the application:willFinishLaunchingWithOptions: method to determine if a URL should be handled. If either method returns NO, the URL is not handled. If you do not implement one of the methods, only the return value of the implemented method is considered.

Availability
  • Available in iOS 3.0 and later.
Declared In
UIApplication.h

application:didReceiveLocalNotification:

Sent to the delegate when a running app receives a local notification.

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
Parameters
application

The app object that received the local notification.

notification

A local notification that encapsulates details about the notification, potentially including custom data.

Discussion

Local notifications are similar to remote push notifications, but differ in that they are scheduled, displayed, and received entirely on the same device. An app can create and schedule a local notification, and the operating system then delivers it at the schedule date and time. If it delivers it when the app is not active in the foreground, it displays an alert, badges the app icon, or plays a sound—whatever is specified in the UILocalNotification object. If the app is running in the foreground, there is no alert, badging, or sound; instead, the application:didReceiveLocalNotification: method is called if the delegate implements it.

The delegate can implement this method if it wants to be notified that a local notification occurred. For example, if the app is a calendar app, it can enumerate its list of calendar events to determine which ones have due dates that have transpired or are about to transpire soon. It can also reset the app icon badge number, and it can access any custom data in the local-notification object’s userInfo dictionary.

This method is called after the application:didFinishLaunchingWithOptions: method (if that method is implemented).

Availability
  • Available in iOS 4.0 and later.
Declared In
UIApplication.h

application:didReceiveRemoteNotification:

Tells the delegate that the running app received a remote notification.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
Parameters
application

The app object that received the remote notification.

userInfo

A dictionary that contains information related to the remote notification, potentially including a badge number for the app icon, an alert sound, an alert message to display to the user, a notification identifier, and custom data. The provider originates it as a JSON-defined dictionary that iOS converts to an NSDictionary object; the dictionary may contain only property-list objects plus NSNull.

Discussion

If the app is running and receives a remote notification, the app calls this method to process the notification. Your implementation of this method should use the notification to take an appropriate course of action. For example, you could use it as a signal to connect to a server and download the data waiting that is waiting for the app.

The userInfo dictionary contains the aps key whose value is another dictionary. Although you should not need the information in the aps dictionary, you can retrieve its contents using the following keys:

  • alert—The value is either a string for the alert message or a dictionary with two keys: body and show-view. The value of the body key is a string containing the alert message and the value of the show-view key is a Boolean. If the value of the show-view key is false, the alert’s View button is not shown. The default is to show the View button which, if the user taps it, launches the app.

  • badge—A number indicating the quantity of data items to download from the provider. This number is to be displayed on the app icon. The absence of a badge property indicates that any number currently badging the icon should be removed.

  • sound—The name of a sound file in the app bundle to play as an alert sound. If “default” is specified, the default sound should be played.

The userInfo dictionary may also have custom data defined by the provider according to the JSON schema. The properties for custom data should be specified at the same level as the aps dictionary. However, custom-defined properties should not be used for mass data transport because there is a strict size limit per notification (256 bytes) and delivery is not guaranteed.

If the app is not running when a push notification arrives, the method launches the app and provides the appropriate information in the launch options dictionary. The app does not call this method to handle that push notification. Instead, your implementation of the application:willFinishLaunchingWithOptions: or application:didFinishLaunchingWithOptions: method needs to get the push notification payload data and respond appropriately.

If your delegate also implements the application:didReceiveRemoteNotification:fetchCompletionHandler: method, the app object calls that method instead of this one.

For more information about how to implement push notifications in your app, see Local and Push Notification Programming Guide.

Availability
  • Available in iOS 3.0 and later.
Declared In
UIApplication.h

application:didReceiveRemoteNotification:fetchCompletionHandler:

Tells the app that a push notification arrived that indicates there is data to be fetched.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
Parameters
application

The singleton app object.

userInfo

A dictionary that contains information related to the remote notification, potentially including a badge number for the app icon, an alert sound, an alert message to display to the user, a notification identifier, and custom data. The provider originates it as a JSON-defined dictionary that iOS converts to an NSDictionary object; the dictionary may contain only property-list objects plus NSNull. For more information about the contents of the push notification dictionary, see Local and Push Notification Programming Guide.

handler

The block to execute when the download operation is complete. When calling this block, pass in the fetch result value that best describes the results of your download operation. You must call this handler and should do so as soon as possible. For a list of possible values, see the UIBackgroundFetchResult type.

Discussion

Implement this method if your app supports the remote-notification background mode. This method is intended as a means for apps to minimize the time that elapses between the user seeing a push notification and the app displaying the associated data. When a push notification arrives, the system displays the notification to the user and launches the app in the background (if needed) so that it can call this method. Use this method to download any data related to the push notification. When your method is done, call the block in the handler parameter.

Unlike the application:didReceiveRemoteNotification: method, which is called only when your app is running, the system calls this method regardless of the state of your app. If your app is suspended or not running, the system wakes up or launches your app and puts it into the background running state before calling the method. If the user opens your app from the system-displayed alert, the system calls this method again so that you know which notification the user selected.

When this method is called, your app has up to 30 seconds of wall-clock time to perform the download operation and call the specified completion handler block. In practice, your app should call the handler block as soon as possible after downloading the needed data. If you do not call the handler in time, your app is terminated. More importantly, the system uses the elapsed time to calculate power usage and data costs for your app’s background downloads. For more information about supporting background operations in response to push notifications, see “App States and Multitasking” in iOS App Programming Guide.

Availability
  • Available in iOS 7.0 and later.
Declared In
UIApplication.h

application:didRegisterForRemoteNotificationsWithDeviceToken:

Tells the delegate that the app successfully registered with Apple Push Service (APS).

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
Parameters
application

The app object that initiated the remote-notification registration process.

deviceToken

A token that identifies the device to APS. The token is an opaque data type because that is the form that the provider needs to submit to the APS servers when it sends a notification to a device. The APS servers require a binary format for performance reasons.

The size of a device token is 32 bytes.

Note that the device token is different from the uniqueIdentifier property of UIDevice because, for security and privacy reasons, it must change when the device is wiped.

Discussion

The delegate receives this message after the registerForRemoteNotificationTypes: method of UIApplication is invoked and there is no error in the registration process. After receiving the device token, the app should connect with its provider and give the token to it. APS only pushes notifications to the app’s device that are accompanied with this token. This method could be called in other rare circumstances, such as when the user launches an app after having restored a device from data that is not the device’s backup data. In this exceptional case, the app won’t know the new device’s token until the user launches it.

For more information about how to implement push notifications in your app, see Local and Push Notification Programming Guide.

Availability
  • Available in iOS 3.0 and later.
Declared In
UIApplication.h

application:handleEventsForBackgroundURLSession:completionHandler:

Tells the delegate that events related to a URL session are waiting to be processed.

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
Parameters
application

The singleton app object.

identifier

The identifier of the URL session requiring attention. If your app was just launched, you can use this identifier to create a new NSURLSession object that can receive the events.

completionHandler

The completion handler to call when you finish processing the events. Calling this completion handler lets the system know that your app’s user interface is updated and a new snapshot can be taken.

Discussion

The app calls this method when all background transfers associated with an NSURLSession object have finished or failed. The app also calls this method if authentication is required for one or more transfers.

Use this method to reconnect any URL sessions and to update your app’s user interface. For example, you might use this method to update progress indicators or to incorporate new content into your views. After processing the events, execute the block in the completionHandler parameter so that the app can take a new snapshot of your user interface.

If a URL session finishes its work when your app is not running, the system launches your app in the background so that it can process the event. In that situation, use the provided identifier to create a new NSURLSessionConfiguration and NSURLSession object. You must configure the other options of your NSURLSessionConfiguration object in the same way that you did when you started the uploads or downloads. Upon creating and configuring the new NSURLSession object, that object calls the appropriate delegate methods to process the events.

If your app already has a session object with the specified identifier and is running or suspended, you do not need to create a new session object using this method. Suspended apps are moved into the background. As soon as the app is running again, the NSURLSession object with the identifier receives the events and processes them normally.

At launch time, the app does not call this method if there are uploads or downloads in progress but not yet finished. If you want to display the current progress of those transfers in your app’s user interface, you must recreate the session object yourself. In that situation, cache the identifier value persistently and use it to recreate your session object.

Availability
  • Available in iOS 7.0 and later.
Declared In
UIApplication.h

application:handleOpenURL:

Asks the delegate to open a resource identified by URL. (Deprecated. Use the application:openURL:sourceApplication:annotation: method instead.)

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
Parameters
application

The singleton app object.

url

A object representing a URL (Universal Resource Locator). See the appendix of iOS App Programming Guide for Apple-registered schemes for URLs.

Return Value

YES if the delegate successfully handled the request; NO if the attempt to handle the URL failed.

Discussion

If the delegate also implements the application:openURL:sourceApplication:annotation: method, that method is called instead of this one.

This method is not called if the delegate returns NO from both the application:willFinishLaunchingWithOptions: and application:didFinishLaunchingWithOptions: methods. (If only one of the two methods is implemented, its return value determines whether this method is called.) If your app implements the applicationDidFinishLaunching: method instead of application:didFinishLaunchingWithOptions:, this method is called to open the specified URL after the app has been initialized.

If a URL arrives while your app is suspended or running in the background, the system moves your app to the foreground prior to calling this method.

There is no equivalent notification for this delegation method.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

application:openURL:sourceApplication:annotation:

Asks the delegate to open a resource identified by URL.

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
Parameters
application

The singleton app object.

url

The URL resource to open. This resource can be a network resource or a file. For information about the Apple-registered URL schemes, see Apple URL Scheme Reference.

sourceApplication

The bundle ID of the app that is requesting your app to open the URL (url).

annotation

A property-list object supplied by the source app to communicate information to the receiving app.

Return Value

YES if the delegate successfully handled the request or NO if the attempt to open the URL resource failed.

Discussion

Your implementation of this method should open the specified URL and update its user interface accordingly. If your app had to be launched to open the URL, the app calls the application:willFinishLaunchingWithOptions: and application:didFinishLaunchingWithOptions: methods first, followed by this method. The return values of those methods can be used to prevent this method from being called. (If the app is already running, only this method is called.)

If the URL refers to a file that was opened through a document interaction controller, the annotation parameter may contain additional data that the source app wanted to send along with the URL. The format of this data is defined by the app that sent it but the data must consist of objects that can be put into a property list.

Files sent to your app through AirDrop or a document interaction controller are placed in the Documents/Inbox directory of your app’s home directory. Your app has permission to read and delete files in this directory but does not have permission to write to them. If you want to modify a file, you must move it to a different directory first. In addition, files in that directory are usually encrypted using data protection. If the file is protected and the user locks the device before this method is called, you will be unable to read the file’s contents immediately. In that case, you should save the URL and try to open the file later rather than return NO from this method. Use the protectedDataAvailable property of the app object to determine if data protection is currently enabled.

There is no matching notification for this method.

Availability
  • Available in iOS 4.2 and later.
Declared In
UIApplication.h

application:performFetchWithCompletionHandler:

Tells the app that it can begin a fetch operation if it has data to download.

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
Parameters
application

The singleton app object.

completionHandler

The block to execute when the download operation is complete. When calling this block, pass in the fetch result value that best describes the results of your download operation. You must call this handler and should do so as soon as possible. For a list of possible values, see the UIBackgroundFetchResult type.

Discussion

Implement this method if your app supports the fetch background mode. When an opportunity arises to download data, the system calls this method to give your app a chance to download any data it needs. Your implementation of this method should download the data, prepare that data for use, and call the block in the completionHandler parameter.

When this method is called, your app has up to 30 seconds of wall-clock time to perform the download operation and call the specified completion handler block. In practice, your app should call the completion handler block as soon as possible after downloading the needed data. If you do not call the completion handler in time, your app is terminated. More importantly, the system uses the elapsed time to calculate power usage and data costs for your app’s background downloads. If your app takes a long time to call the completion handler, it may be given fewer future opportunities to fetch data in the future. For more information about supporting background fetch operations, see “App States and Multitasking” in iOS App Programming Guide.

Availability
  • Available in iOS 7.0 and later.
Declared In
UIApplication.h

application:shouldRestoreApplicationState:

Asks the delegate whether the app’s saved state information should be restored.

- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
Parameters
application

The singleton app object.

coder

The keyed archiver containing the app’s previously saved state information.

Return Value

YES if the app’s state should be restored or NO if it should not.

Discussion

Apps must implement this method and the application:shouldSaveApplicationState: method for state preservation to occur. In addition, your implementation of this method must return YES each time UIKit tries to restore the state of your app. You can use the information in the provided coder object to decide whether or not to proceed with state restoration. For example, you might return NO if the data in the coder is from a different version of your app and cannot be effectively restored to the current version.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

application:shouldSaveApplicationState:

Asks the delegate whether the app’s state should be preserved.

- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
Parameters
application

The singleton app object.

coder

The keyed archiver into which you can put high-level state information.

Return Value

YES if the app’s state should be preserved or NO if it should not.

Discussion

Apps must implement this method and the application:shouldRestoreApplicationState: method for state preservation to occur. In addition, your implementation of this method must return YES each time UIKit tries to preserve the state of your app. You can return NO to disable state preservation temporarily. For example, during testing, you could disable state preservation to test specific code paths.

You can add version information or any other contextual data to the provided coder object as needed. During restoration, you can use that information to help decide whether or not to proceed with restoring your app to its previous state.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

application:supportedInterfaceOrientationsForWindow:

Asks the delegate for the interface orientations to use for the view controllers in the specified window.

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
Parameters
application

The singleton app object.

window

The window whose interface orientations you want to retrieve.

Return Value

A bit mask of the UIInterfaceOrientationMask constants that indicate the orientations to use for the view controllers.

Discussion

This method returns the total set of interface orientations supported by the app. When determining whether to rotate a particular view controller, the orientations returned by this method are intersected with the orientations supported by the root view controller or topmost presented view controller. The app and view controller must agree before the rotation is allowed.

If you do not implement this method, the app uses the values in the UIInterfaceOrientation key of the app’s Info.plist as the default interface orientations.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

application:viewControllerWithRestorationIdentifierPath:coder:

Asks the delegate to provide the specified view controller.

- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
Parameters
application

The singleton app object.

identifierComponents

An array of NSString objects corresponding to the restoration identifiers of the desired view controller and all of its ancestors in the view controller hierarchy. The last value in the array is the restoration identifier of the desired view controller. Earlier entries represent the restoration identifiers of its ancestors.

coder

The keyed archiver containing the app’s saved state information.

Return Value

The view controller object to use or nil if you do not want to restore this view controller or its children.

For view controllers that are children of a common parent, returning nil for one child may prevent others from being restored too. For example, in a navigation controller, returning nil for a view controller in the middle of the navigation stack prevents the restoration of view controllers higher up on the stack.

Discussion

During state restoration, when UIKit encounters a view controller without a restoration class, it calls this method to ask for the corresponding view controller object. Your implementation of this method should create (or find) the corresponding view controller object and return it. If you determine that it does not make sense to display this view controller now, you may return nil to prevent that view controller from being added to your interface as part of the restoration process.

You use the strings in the identifierComponents parameter to identify the view controller being requested. The view controllers in your app form a hierarchy. At the root of this hierarchy is the window’s root view controller, which itself may present or embed other view controllers. Those presented or embedded view controllers may themselves present and embed other view controllers. The result is a hierarchy of view controller relationships, with each presented or embedded view controller becoming a child of the view controller that presented or embedded it. The strings in the identifierComponents array identify the path through this hierarchy from the root view controller to the desired view controller.

It is not always necessary to create a new view controller object in your implementation of this method. You can also return an existing view controller object that was created by another means. For example, you would always return the existing view controllers loaded from your app’s main storyboard file rather than create new objects.

Your implementation of this method may use any data in the provided coder to assist in the restoration process. However, you usually do not need to restore the entire state of the view controller at this point. During a later pass, view controllers that define a decodeRestorableStateWithCoder: method are normally given a chance to restore their state form the same coder object. Similarly, the app delegate itself has a application:didDecodeRestorableStateWithCoder: method that you can use to restore app-level state information.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

application:willChangeStatusBarFrame:

Tells the delegate when the frame of the status bar is about to change.

- (void)application:(UIApplication *)application willChangeStatusBarFrame:(CGRect)newStatusBarFrame
Parameters
application

The singleton app object.

newStatusBarFrame

The changed frame of the status bar, in screen coordinates.

Discussion

The app calls this method when it receives a setStatusBarOrientation:animated: message and is about to change the interface orientation.

After calling this method, the app also posts a UIApplicationWillChangeStatusBarFrameNotification notification to give interested objects a chance to respond to the change.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

application:willChangeStatusBarOrientation:duration:

Tells the delegate when the interface orientation of the status bar is about to change.

- (void)application:(UIApplication *)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
Parameters
application

The singleton app object.

newStatusBarOrientation

A constant that indicates the new orientation of the app’s user interface; see “Monitoring App State Changes” for details.

duration

The duration of the animation to the new orientation, in seconds.

Discussion

The delegate typically implements this method to prepare its windows and views for the new orientation. The delegate can get the current device orientation from the shared UIDevice object.

After calling this method, the app also posts a UIApplicationWillChangeStatusBarOrientationNotification notification to give interested objects a chance to respond to the change.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

application:willEncodeRestorableStateWithCoder:

Tells your delegate to save any high-level state information at the beginning of the state preservation process.

- (void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder
Parameters
application

The singleton app object.

coder

The keyed archiver in which to write any state information.

Discussion

The state preservation system calls this method at the beginning of the preservation process. This is your opportunity to add any app-level information to state information. For example, you might use this method to write version information or the high-level configuration of your app.

Your implementation of this method can encode restorable view and view controller objects that it needs to reference. Encoding a restorable view or view controller writes that object’s restoration identifier to the coder. (That identifier is used during the decode process to locate the new version of the object.) If the view or view controller defines a encodeRestorableStateWithCoder: method, that method is also called at some point so that the object can encode its own state.

Apart from views and view controllers, other objects follow the normal serialization process and must adopt the NSCoding protocol before they can be encoded. Encoding such objects embeds the object’s contents in the archive directly. During the decode process, a new object is created and initialized with the data from the archive.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

application:willFinishLaunchingWithOptions:

Tells the delegate that the launch process has begun but that state restoration has not yet occurred.

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Parameters
application

The singleton app object.

launchOptions

A dictionary indicating the reason the app was launched (if any). The contents of this dictionary may be empty in situations where the user launched the app directly. For information about the possible keys in this dictionary and how to handle them, see “Launch Options Keys.”

Return Value

NO if the app cannot handle the URL resource, otherwise return YES. The return value is ignored if the app is launched as a result of a remote notification.

Discussion

You should use this method (and the corresponding application:didFinishLaunchingWithOptions: method) to initialize your app and prepare it to run. This method is called after your app has been launched and its main storyboard or nib file has been loaded, but before your app’s state has been restored. At the time this method is called, your app is in the inactive state.

If your app was launched by the system for a specific reason, the launchOptions dictionary contains data indicating the reason for the launch. Your app should look in this dictionary for any keys that correspond to features your app supports. If the given key is present, you should provide an appropriate response.

If your app was launched to open a URL, you should examine the value of the UIApplicationLaunchOptionsURLKey key and return a Boolean value indicating whether your app can actually open the URL. You should not try to open the URL in this method. Instead, implement the application:openURL:sourceApplication:annotation: method in your app delegate and use that method to open the URL.

The return result from this method is combined with the return result from the application:didFinishLaunchingWithOptions: method to determine if a URL should be handled. If either method returns NO, the URL is not handled. If you do not implement one of the methods, only the return value of the implemented method is considered.

Availability
  • Available in iOS 6.0 and later.
Declared In
UIApplication.h

applicationDidBecomeActive:

Tells the delegate that the app has become active.

- (void)applicationDidBecomeActive:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

This method is called to let your app know that it moved from the inactive to active state. This can occur because your app was launched by the user or the system. Apps can also return to the active state if the user chooses to ignore an interruption (such as an incoming phone call or SMS message) that sent the app temporarily to the inactive state.

You should use this method to restart any tasks that were paused (or not yet started) while the app was inactive. For example, you could use it to restart timers or throttle up OpenGL ES frame rates. If your app was previously in the background, you could also use it to refresh your app’s user interface.

After calling this method, the app also posts a UIApplicationDidBecomeActiveNotification notification to give interested objects a chance to respond to the transition.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

applicationDidEnterBackground:

Tells the delegate that the app is now in the background.

- (void)applicationDidEnterBackground:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

In iOS 4.0 and later, this method is called instead of the applicationWillTerminate: method when the user quits an app that supports background execution. You should use this method to release shared resources, save user data, invalidate timers, and store enough app state information to restore your app to its current state in case it is terminated later. You should also disable updates to your app’s user interface and avoid using some types of shared system resources (such as the user’s contacts database). It is also imperative that you avoid using OpenGL ES in the background.

Your implementation of this method has approximately five seconds to perform any tasks and return. If you need additional time to perform any final tasks, you can request additional execution time from the system by calling beginBackgroundTaskWithExpirationHandler:. In practice, you should return from applicationDidEnterBackground: as quickly as possible. If the method does not return before time runs out your app is terminated and purged from memory.

You should perform any tasks relating to adjusting your user interface before this method exits but other tasks (such as saving state) should be moved to a concurrent dispatch queue or secondary thread as needed. Because it's likely any background tasks you start in applicationDidEnterBackground: will not run until after that method exits, you should request additional background execution time before starting those tasks. In other words, first call beginBackgroundTaskWithExpirationHandler: and then run the task on a dispatch queue or secondary thread.

The app also posts a UIApplicationDidEnterBackgroundNotification notification around the same time it calls this method to give interested objects a chance to respond to the transition.

For more information about how to transition gracefully to the background, and for information about how to start background tasks at quit time, see iOS App Programming Guide.

Availability
  • Available in iOS 4.0 and later.
Declared In
UIApplication.h

applicationDidFinishLaunching:

Tells the delegate when the app has finished launching.

- (void)applicationDidFinishLaunching:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

This method is used in earlier versions of iOS to initialize the app and prepare it to run. In iOS 3.0 and later, you should use the application:didFinishLaunchingWithOptions: instead. In iOS 6.0 and later, you may also use the application:willFinishLaunchingWithOptions: method to initialize your app.

Your implementation of this method should create your app’s user interface and initialize the app’s data structures. If your app persists its state between launches, you would also use this method to restore your app to its previous state.

After calling this method, the app also posts a UIApplicationDidFinishLaunchingNotification notification to give interested objects a chance to respond to the initialization cycle.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

applicationDidReceiveMemoryWarning:

Tells the delegate when the app receives a memory warning from the system.

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

Your implementation of this method should free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. You use this method in conjunction with the didReceiveMemoryWarning of the UIViewController class and the UIApplicationDidReceiveMemoryWarningNotification notification to release memory throughout your app.

It is strongly recommended that you implement this method. If your app does not release enough memory during low-memory conditions, the system may terminate it outright.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

applicationProtectedDataDidBecomeAvailable:

Tells the delegate that protected files are available now.

- (void)applicationProtectedDataDidBecomeAvailable:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

On a device that uses content protection, protected files are stored in an encrypted form and made available only at certain times, usually when the device is unlocked. This notification lets your app know that the device is now unlocked and that you may access certain types of protected files again.

Availability
  • Available in iOS 4.0 and later.
Declared In
UIApplication.h

applicationProtectedDataWillBecomeUnavailable:

Tells the delegate that the protected files are about to become unavailable.

- (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

On a device that uses content protection, protected files are stored in an encrypted form and made available only at certain times, usually when the device is unlocked. This notification lets your app know that the device is about to be locked and that any protected files it is currently accessing might become unavailable shortly.

If your app is currently accessing a protected file, you can use this method to release any references to that file. Although it is not an error to access the file while the device is locked, any attempts to do so will fail. Therefore, if your app depends on the file, you might want to take steps to avoid using that file while the device is locked.

Availability
  • Available in iOS 4.0 and later.
Declared In
UIApplication.h

applicationSignificantTimeChange:

Tells the delegate when there is a significant change in the time.

- (void)applicationSignificantTimeChange:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

Examples of significant time changes include the arrival of midnight, an update of the time by a carrier, and the change to daylight savings time. The delegate can implement this method to adjust any object of the app that displays time or is sensitive to time changes.

Prior to calling this method, the app also posts a UIApplicationSignificantTimeChangeNotification notification to give interested objects a chance to respond to the change.

If your app is currently suspended, this message is queued until your app returns to the foreground, at which point it is delivered. If multiple time changes occur, only the most recent one is delivered.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

applicationWillEnterForeground:

Tells the delegate that the app is about to enter the foreground.

- (void)applicationWillEnterForeground:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

In iOS 4.0 and later, this method is called as part of the transition from the background to the active state. You can use this method to undo many of the changes you made to your app upon entering the background. The call to this method is invariably followed by a call to the applicationDidBecomeActive: method, which then moves the app from the inactive to the active state.

The app also posts a UIApplicationWillEnterForegroundNotification notification shortly before calling this method to give interested objects a chance to respond to the transition.

Availability
  • Available in iOS 4.0 and later.
Declared In
UIApplication.h

applicationWillResignActive:

Tells the delegate that the app is about to become inactive.

- (void)applicationWillResignActive:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

This method is called to let your app know that it is about to move from the active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the app and it begins the transition to the background state. An app in the inactive state continues to run but does not dispatch incoming events to responders.

You should use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. An app in the inactive state should do minimal work while it waits to transition to either the active or background state.

After calling this method, the app also posts a UIApplicationWillResignActiveNotification notification to give interested objects a chance to respond to the transition.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

applicationWillTerminate:

Tells the delegate when the app is about to terminate.

- (void)applicationWillTerminate:(UIApplication *)application
Parameters
application

The singleton app object.

Discussion

This method lets your app know that it is about to be terminated and purged from memory entirely. You should use this method to perform any final clean-up tasks for your app, such as freeing shared resources, saving user data, and invalidating timers. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

For apps that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the app. For apps that support background execution, this method is generally not called when the user quits the app because the app simply moves to the background in that case. However, this method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.

After calling this method, the app also posts a UIApplicationWillTerminateNotification notification to give interested objects a chance to respond to the transition.

Availability
  • Available in iOS 2.0 and later.
Declared In
UIApplication.h

Constants

Launch Options Keys

Keys used to access values in the launch options dictionary passed to the application:willFinishLaunchingWithOptions: and application:didFinishLaunchingWithOptions: methods of the app delegate.

NSString *const UIApplicationLaunchOptionsURLKey;
NSString *const UIApplicationLaunchOptionsSourceApplicationKey;
NSString *const UIApplicationLaunchOptionsRemoteNotificationKey;
NSString *const UIApplicationLaunchOptionsAnnotationKey;
NSString *const UIApplicationLaunchOptionsLocalNotificationKey;
NSString *const UIApplicationLaunchOptionsLocationKey;
NSString *const UIApplicationLaunchOptionsNewsstandDownloadsKey;
NSString *const UIApplicationLaunchOptionsBluetoothCentralsKey;
NSString *const UIApplicationLaunchOptionsBluetoothPeripheralsKey;
Constants
UIApplicationLaunchOptionsURLKey

The presence of this key indicates that the app was launched in order to open a URL. The value of this key is an NSURL object containing the URL to open.

This key is also used to access the same value in the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.

Available in iOS 3.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsSourceApplicationKey

The presence of this key identifies the app that requested the launch of your app. The value of this key is an NSString object that represents the bundle ID of the app that made the request.

This key is also used to access the same value in the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.

Available in iOS 3.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsRemoteNotificationKey

The presence of this key indicates that a remote notification is available for the app to process. The value of this key is an NSDictionary containing the payload of the remote notification. See the description of application:didReceiveRemoteNotification: for further information about handling remote notifications.

This key is also used to access the same value in the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.

Available in iOS 3.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsAnnotationKey

The presence of this key indicates that custom data was provided by the app that requested the opening of the URL. The value of this key is a property-list object containing the custom data. The same object is also passed to the annotation parameter of the application:openURL:sourceApplication:annotation: method. The contents of this property-list object are specific to the app that made the request.

Available in iOS 3.2 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsLocalNotificationKey

The presence of this key indicates that a local notification is available for the app to process. The value of this key is the UILocalNotification object that was triggered. For additional information about handling local notifications, see the application:didReceiveLocalNotification: method.

This key is also used to access the same value in the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.

Available in iOS 4.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsLocationKey

The presence of this key indicates that the app was launched in response to an incoming location event. The value of this key is an NSNumber object containing a Boolean value. You should use the presence of this key as a signal to create a CLLocationManager object and start location services again. Location data is delivered only to the location manager delegate and not using this key.

Available in iOS 4.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsNewsstandDownloadsKey

The presence of this key indicates that newly downloaded Newsstand assets are available for your app. The value of this key is an array of string identifiers that identify the NKAssetDownload objects corresponding to the assets. Although you can use the identifiers for cross-checking purposes, you should obtain the definitive array of NKAssetDownload objects (representing asset downloads in progress or in error) through the downloadingAssets property of the NKLibrary object representing the Newsstand app’s library.

Available in iOS 5.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsBluetoothCentralsKey

The presence of this key indicates that the app previously had one or more CBCentralManager objects and was relaunched by the Bluetooth system to continue actions associated with those objects. The value of this key is an NSArray object containing one or more NSString objects.

Each string in the array represents the restoration identifier for a central manager object. This is the same string you assigned to the CBCentralManagerOptionRestoreIdentifierKey key when you initialized the central manager object previously. The system provides the restoration identifiers only for central managers that had active or pending peripheral connections or were scanning for peripherals.

Available in iOS 7.0 and later.

Declared in UIApplication.h.

UIApplicationLaunchOptionsBluetoothPeripheralsKey

The presence of this key indicates that the app previously had one or more CBPeripheralManager objects and was relaunched by the Bluetooth system to continue actions associated with those objects. The value of this key is an NSArray object containing one or more NSString objects.

Each string in the array represents the restoration identifier for a peripheral manager object. This is the same string you assigned to the CBPeripheralManagerOptionRestoreIdentifierKey key when you initialized the peripheral manager object previously. The system provides the restoration identifiers only for peripheral managers that had published or advertised services.

Available in iOS 7.0 and later.

Declared in UIApplication.h.