Protocol

UIApplicationDelegate

The UIApplicationDelegate protocol defines methods that are called by the singleton UIApplication object in response to important events in the lifetime of your app.

Overview

The app delegate works alongside the app object to ensure your app interacts properly with the system and with other apps. Specifically, the methods of the app delegate give you a chance to respond to important changes. For example, you use the methods of the app delegate to respond to state transitions, such as when your app moves from foreground to background execution, and to respond to incoming notifications. In many cases, the methods of the app delegate are the only way to receive these important notifications.

Xcode provides an app delegate class for every new project, so you do not need to define one yourself initially. When your app launches, UIKit automatically creates an instance of the app delegate class provided by Xcode and uses it to execute the first bits of custom code in your app. All you have to do is take the class that Xcode provides and add your custom code.

The app delegate is effectively the root object of your app. Like the UIApplication object itself, the app delegate is a singleton object and is always present at runtime. Although the UIApplication object does most of the underlying work to manage the app, you decide your app’s overall behavior by providing appropriate implementations of the app delegate’s methods. Although most methods of this protocol are optional, you should implement most or all of them.

The app delegate performs several crucial roles:

  • It contains your app’s startup code.

  • It responds to key changes in the state of your app. Specifically, it responds to both temporary interruptions and to changes in the execution state of your app, such as when your app transitions from the foreground to the background.

  • It responds to notifications originating from outside the app, such as remote notifications (also known as push notifications), low-memory warnings, download completion notifications, and more.

  • It determines whether state preservation and restoration should occur and assists in the preservation and restoration process as needed.

  • It responds to events that target the app itself and are not specific to your app’s views or view controllers.

  • You can use it to store your app’s central data objects or any content that does not have an owning view controller.

For more information about the role of the app delegate and how it fits into the app architecture, see App Programming Guide for iOS. For more information about the UIApplication singleton class, see UIApplication.

Starting Up Your App

Launch time is an important point in an app’s life cycle. At launch time, the app delegate is responsible for executing any custom code required to initialize your app. For example, the app delegate typically creates the app’s initial data structures, registers for any required services, and tweaks the app’s initial user interface based on any available data.

Some additional tasks that the app delegate performs at launch time include the following:

  • Look at the launch options dictionary to determine why your app was launched. The application(_:willFinishLaunchingWithOptions:) and application(_:didFinishLaunchingWithOptions:) methods provide a dictionary with keys indicating the reason that your app was launched.

  • Determine whether state restoration should proceed. If the app previously saved the state of its view controllers, restoration of those view controllers to their previous state proceeds only if the app delegate’s application(_:shouldRestoreApplicationState:) method returns true.

  • Register for any remote notifications your app supports. In order to receive remote notifications (also known as push notifications), an app must register with the remote notification service by calling the registerForRemoteNotifications(matching:) method of the UIApplication object. Usually, you perform this task at launch time.

  • Open a URL that was sent to your app. If there is a URL to open, the system calls the application(_:open:options:) method of your app delegate. You can also tell if there is a URL to open by looking in the launch options dictionary for the url key. You must declare the types of URLs your app supports by adding the CFBundleURLTypes key to your app’s Info.plist file. For more information about registering and handling URLs, see App Programming Guide for iOS.

  • Provide the root window object for your app. Technically, the app delegate provided by Xcode already implements the window property, so you do not have to do anything special here unless you want to customize your app’s window.

The options dictionary passed to the application(_:willFinishLaunchingWithOptions:) and application(_:didFinishLaunchingWithOptions:) methods is an important source of launch-time information for your app. The keys in that dictionary tell you the reason your app was launched and give you a chance to adjust your launch procedures accordingly. For example, if your app was launched because of an incoming remote notification, you might want to reconfigure your user interface to display data related to that notification. For a list of possible reasons why your app might be launched, see Launch Options Keys.

Managing State Transitions

One of the main jobs of the app delegate is to respond to state transitions reported by the system. For every state change that occurs, the system calls the appropriate methods of the app delegate. Each state has different rules that govern how the app should is expected to behave and the app delegate methods must adjust the behavior of the app accordingly. Table 1 lists the possible states of an app and the high-level expectations. Figure 1 shows how an app moves from one state to another.

Table 1

App states

State

Description

Not running

The app has not been launched or was terminated, either by the user or the system.

Inactive

The app is running in the foreground but is not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.

Upon entering this state, the app should put itself into a quiescent state with the expectation of moving to the background or active state shortly.

Active

The app is running in the foreground and receiving events. This is the normal mode for foreground apps.

An app in the active state has no special restrictions placed on it. It is the foreground app and should be responsive to the user.

Background

The app is executing code but is not visible onscreen. When the user quits an app, the system moves the app to the background state briefly before suspending it. At other times, the system may launch the app into the background (or wake up a suspended app) and give it time to handle specific tasks. For example, the system may wake up an app so that it can process background downloads, certain types of location events, remote notifications, and other types of events.

An app in the background state should do as little work as possible. Apps that request time to process specific types of events should process those events and return control back to the system as quickly as possible.

Suspended

The app is in memory but is not executing code. The system suspends apps that are in the background and do not have any pending tasks to complete. The system may purge suspended apps at any time without waking them up to make room for other apps.

Figure 1

State changes in an iOS app

The following methods are called when state transitions occur. For information about what to do in response to each transition, see the method descriptions listed for each state.

The specific tasks you perform during a given state transition are dependent upon your app and its capabilities. For tips and guidance about what to do during state transitions, see App Programming Guide for iOS.

Responding to Notifications and Events

The system sends many different notifications and events to the app delegate, letting the app delegate decide how best to respond to the incoming information and update the app. Most of these notifications correspond to app-level behaviors that might require you to update your app’s data or user interface or respond to a changed condition of the system. The way you handle these notifications depends on the architecture of your app. In many cases, the app delegate might not do anything more than notify other objects (such as your app’s view controllers) that they need to update themselves, but in some cases the app delegate might do the work itself.

Symbols

Responding to App State Changes and System Events

func application(UIApplication, willFinishLaunchingWithOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)

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

func application(UIApplication, didFinishLaunchingWithOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)

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

func applicationDidFinishLaunching(UIApplication)

Tells the delegate when the app has finished launching. Don’t use. Instead, use application(_:didFinishLaunchingWithOptions:).

func applicationDidBecomeActive(UIApplication)

Tells the delegate that the app has become active.

func applicationWillResignActive(UIApplication)

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

func applicationDidEnterBackground(UIApplication)

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

func applicationWillEnterForeground(UIApplication)

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

func applicationWillTerminate(UIApplication)

Tells the delegate when the app is about to terminate.

func applicationProtectedDataWillBecomeUnavailable(UIApplication)

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

func applicationProtectedDataDidBecomeAvailable(UIApplication)

Tells the delegate that protected files are available now.

func applicationDidReceiveMemoryWarning(UIApplication)

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

func applicationSignificantTimeChange(UIApplication)

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

Managing App State Restoration

func application(UIApplication, shouldSaveApplicationState: NSCoder)

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

func application(UIApplication, shouldRestoreApplicationState: NSCoder)

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

func application(UIApplication, willEncodeRestorableStateWith: NSCoder)

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

func application(UIApplication, didDecodeRestorableStateWith: NSCoder)

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

Downloading Data in the Background

func application(UIApplication, performFetchWithCompletionHandler: (UIBackgroundFetchResult) -> Void)

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

func application(UIApplication, handleEventsForBackgroundURLSession: String, completionHandler: () -> Void)

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

Handling Local and Remote Notifications

func application(UIApplication, didRegister: UIUserNotificationSettings)

Called to tell the delegate the types of local and remote notifications that can be used to get the user’s attention.

func application(UIApplication, didReceive: UILocalNotification)

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

Deprecated
func application(UIApplication, handleActionWithIdentifier: String?, for: UILocalNotification, completionHandler: () -> Void)

Called when your app has been activated because user selected a custom action from the alert panel of a local notification.

Deprecated
func application(UIApplication, didRegisterForRemoteNotificationsWithDeviceToken: Data)

Tells the delegate that the app successfully registered with Apple Push Notification service (APNs).

func application(UIApplication, didFailToRegisterForRemoteNotificationsWithError: Error)

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

func application(UIApplication, handleActionWithIdentifier: String?, forRemoteNotification: [AnyHashable : Any], completionHandler: () -> Void)

Tells the app delegate to perform the custom action specified by a remote notification.

Deprecated
func application(UIApplication, didReceiveRemoteNotification: [AnyHashable : Any])

Called when your app has received a remote notification.

Deprecated

Continuing User Activity and Handling Quick Actions

func application(UIApplication, willContinueUserActivityWithType: String)

Tells the delegate if your app takes responsibility for notifying users when a continuation activity takes longer than expected.

func application(UIApplication, continue: NSUserActivity, restorationHandler: ([Any]?) -> Void)

Tells the delegate that the data for continuing an activity is available.

func application(UIApplication, didUpdate: NSUserActivity)

Tells the delegate that the activity was updated.

func application(UIApplication, performActionFor: UIApplicationShortcutItem, completionHandler: (Bool) -> Void)

Called when the user selects a Home screen quick action for your app, except when you’ve intercepted the interaction in a launch method.

Interacting With WatchKit

Interacting With HealthKit

func applicationShouldRequestHealthAuthorization(UIApplication)

Called when your app should ask the user for access to his or her HealthKit data.

Opening a URL-Specified Resource

func application(UIApplication, open: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])

Asks the delegate to open a resource specified by a URL, and provides a dictionary of launch options.

Disallowing Specified App Extension Types

func application(UIApplication, shouldAllowExtensionPointIdentifier: UIApplicationExtensionPointIdentifier)

Asks the delegate to grant permission to use app extensions that are based on a specified extension point identifier.

Managing Interface Geometry

func application(UIApplication, supportedInterfaceOrientationsFor: UIWindow?)

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

func application(UIApplication, willChangeStatusBarOrientation: UIInterfaceOrientation, duration: TimeInterval)

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

func application(UIApplication, didChangeStatusBarOrientation: UIInterfaceOrientation)

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

func application(UIApplication, willChangeStatusBarFrame: CGRect)

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

func application(UIApplication, didChangeStatusBarFrame: CGRect)

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

Providing a Window for Storyboarding

var window: UIWindow?

The window to use when presenting a storyboard.

Deprecated Methods

func application(UIApplication, handleOpen: URL)

Asks the delegate to open a resource identified by URL.

Deprecated
func application(UIApplication, open: URL, sourceApplication: String?, annotation: Any)

Asks the delegate to open a resource identified by a URL.

Deprecated

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.

URL Handling Keys

Keys used to access values in the options dictionary passed to the application(_:open:options:) method of the app delegate.

Relationships

Inherits From