Protocol

WKExtensionDelegate

A collection of methods you can implement to manage the app-level behavior of your WatchKit extension.

Overview

You can use the delegate to respond to actionable notifications and manage Handoff transitions. You also use the delegate to respond to life-cycle events, such as the activation and deactivation of your app.

WatchKit creates your delegate object automatically by instantiating the class assigned to the WKExtensionDelegateClassName key in your WatchKit extension’s Info.plist file. The delegate object is then assigned to the delegate property of the shared WKExtension object.

Managing State Transitions

WatchKit reports changes in your app’s execution state to your extension delegate object. State changes correspond to major events in the lifetime of your app. The state changes in a Watch app are analogous to the state changes of an iOS app. For each state change, perform relevant tasks, such as loading shared resources and configuring your initial user interface. Table 1 lists the possible state of the app and the implications for your app. Figure 1 shows the state changes that occur for a Watch app and the delegate methods that are called when those changes occur.

Table 1

Extension states

State

Description

Not running

The Watch app has not been launched or was terminated by the system.

Inactive

The Watch app is running in the foreground but is not receiving events. (It may be executing other code though.) A newly launched app usually stays in this state only briefly as it transitions to the active state. An active app that transitions to this state should quiet itself and prepare to be terminated shortly.

Active

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

Background

The Watch app has been given a small amount of background execution time to fetch updated data from the network.

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 to make room for other apps. The system silently purges suspended apps. The suspended apps do not wake, and do not receive any notifications before being purged.

The system tries to keep frequently used apps in memory, allowing them to resume as quickly as possible. Specifically, the system preserves the most recently executed app, any apps that are in the Dock, and any apps that have a complication on the currently active watch face. If memory constraints force the system to purge one of these apps, the system will relaunch the app as soon as more memory becomes available.

Figure 1

State changes in a Watch app

State transition events occur only for the Watch’s main interface. They do not occur when any other supplementary interfaces are displayed. For example, they do not occur when the app is launched to update complications or display custom notification interfaces. For notifications, use the controller’s willActivate() and didDeactivate() methods to track the state of the interface.

Snapshots

Glances are no longer supported in watchOS 3.0 and later. Instead, the system uses snapshots and the dock to provide a glimpse of your application’s current state.

The system uses snapshots in two ways:

  • The system uses a snapshot to represent your app in the dock.

    The system displays the dock when the user presses the watch’s side button. The dock contains up to ten apps selected by the user. The user can scroll between these apps. If the user lets the dock settle on an app for a moment, that app’s snapshot is replaced by a running instance of the app.

    The system tries to keep these apps in memory so that they resume quickly. These apps also receive priority for background tasks, helping you keep their content up to date.

  • The system uses your app’s snapshot as its launch image. It displays this image as the app launches. As soon as the app is active, it replaces the snapshot with the app’s live user interface.

Use Background Snapshot Refresh Tasks to control which interface controller is displayed in the snapshot, and to update the controller’s content before a snapshot is taken. For more information, see Background Refresh Tasks.

Background Refresh Tasks

Background tasks give your app a small amount of time (on the order of seconds) to run in the background. Different tasks types are provided. Each task type handles a specific type of background activity. You can schedule some of these tasks. Others are automatically scheduled by the system.

All background tasks follow the same general procedure:

  1. The system wakes your extension in the background and calls your delegate’s handle(_:) method. The handle(_:) method is passed a set containing one or more background tasks.

  2. For each task in the set, check the tasks type, and perform the appropriate actions.

  3. After the task is complete, call the task’s setTaskCompleted method. The system suspends the app again as soon as all background tasks are complete.

If you implement your delegate’s handle(_:) method, you will receive all the background tasks, both those that you schedule and those scheduled by the system. Some of your app’s other behaviors also change:

  • Background Watch Connectivity transfers wake your app, triggering a background watch connectivity task. Use this task to receive the data and update your app’s state.

  • Background NSURLSession transfers wake your app when the transfer needs authorization or when the transfer completes (successfully or not). You can use this task to authorize the transfer or to update your app’s state.

  • The system no longer calls your CLKComplicationDataSource object’s getNextRequestedUpdateDate(handler:), requestedUpdateDidBegin(), or requestedUpdateBudgetExhausted() methods. You must schedule a background app refresh task to update your complication instead.

Due to the asynchronous nature of these tasks, your handle(_:) method may be called with multiple tasks. It may be called while you are currently handling other background tasks, and it may even be called while your app is in the foreground. Your code must handle all of these cases. Fortunately, if handle(_:) is called while your app is in the foreground, you can often ignore the tasks, just call setTaskCompleted, and return.

Background App Refresh Tasks

Use this task to update your app’s state in the background. You often use a background app refresh task to drive other tasks. For example, you could use a background app refresh task to start an URLSession background transfer, or to schedule a background snapshot refresh task.

Your app must schedule background app refresh tasks by calling your extension’s scheduleBackgroundRefresh(withPreferredDate:userInfo:scheduledCompletion:) method. The system never schedules these tasks.

For more information, see WKApplicationRefreshBackgroundTask.

Background Snapshot Refresh Tasks

Use this task to update your app’s user interface. You can push, pop, or present other interface controllers, and then update the content of the desired interface controller. The system automatically takes a snapshot of your user interface as soon as this task completes.

Your app can invalidate its current snapshot and schedule a background snapshot refresh tasks by calling your extension’s scheduleSnapshotRefresh(withPreferredDate:userInfo:scheduledCompletion:) method. The system will also schedule background snapshot refresh tasks to periodically update your snapshot.

For more information, see WKSnapshotRefreshBackgroundTask.

For more information about snapshots, see Snapshots.

Background Watch Connectivity Tasks

This task is triggered when your app receives background data from the paired iPhone. Use this task to receive the data. Background watch connectivity tasks are only scheduled by the system.

For more information, see WKWatchConnectivityRefreshBackgroundTask.

Background NSURLSession Tasks

This task is triggered when a background transfer requires authorization, or when a background transfer completes (successfully or unsuccessfully). Background NSURLSession Tasks are only scheduled by the system.

For more information, see WKURLSessionRefreshBackgroundTask.

Topics

Monitoring State Changes

func applicationDidFinishLaunching()

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

func applicationDidBecomeActive()

Tells the delegate that the Watch app is now visible and processing events.

func applicationWillResignActive()

Tells the delegate that the Watch app is about to be deactivated.

func applicationWillEnterForeground()

Tells the delegate that the app is about to transition from the background to the foreground.

func applicationDidEnterBackground()

Tells the delegate that the app has transitioned from the foreground to the background.

func handle(Set<WKRefreshBackgroundTask>)

Tells the delegate that the app has received one or more background tasks.

Responding to Notifications

func didReceiveRemoteNotification([AnyHashable : Any])

Tells the delegate that a remote notification arrived.

Deprecated
func didReceive(UILocalNotification)

Tells the delegate that a local notification was triggered.

Deprecated
func handleAction(withIdentifier: String?, forRemoteNotification: [AnyHashable : Any])

Delivers a remote notification payload and a user-selected action to the app.

Deprecated
func handleAction(withIdentifier: String?, forRemoteNotification: [AnyHashable : Any], withResponseInfo: [AnyHashable : Any])

Delivers a remote notification payload and user response information to the app.

Deprecated
func handleAction(withIdentifier: String?, for: UILocalNotification)

Delivers a local notification payload and a user-selected action to the app.

Deprecated
func handleAction(withIdentifier: String?, for: UILocalNotification, withResponseInfo: [AnyHashable : Any])

Delivers a local notification payload and user response information to the app.

Deprecated

Handling a Workout Session

func handle(HKWorkoutConfiguration)

Tells the delegate that the user started a workout session on the paired iPhone.

Coordinating Handoff Activity

func handleUserActivity([AnyHashable : Any]?)

Responds to Handoff–related activity.

Instance Methods

func handle(NSUserActivity)

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

Relationships

Inherits From

See Also

Extension Architecture

class WKExtension

An object that manages behaviors that are shared among all of your app’s interface controllers.

class WKInterfaceDevice

An object that provides information about the user’s Apple Watch.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software