A class for scheduling tasks run by submitting task requests that launch your app in the background.
- iOS 13.0+
- Mac Catalyst 13.0+
- tvOS 13.0+
A task is a standalone activity, such as cleaning a database, updating a machine learning model, or updating the displayed data for an app. To make efficient use of processing time and power, the system can launch your app in the background to run tasks like these when the device isn’t in use.
A task can run many times and requires:
Configuring the app to enable background task execution.
Registering a launch handler for the task.
Scheduling the task.
Configuring the App for Background Tasks
Configure the app for background tasks by adding the capabilities for the required background modes, and by adding a whitelist of task identifiers.
To add the capabilities:
Open the project editor and select the desired target.
Click Signing & Capabilities.
Expand the Background Modes section. If there’s no Background Modes section, click the “+ Capability” button and choose Background Modes in the window that appears.
Select one or both of Background fetch and Background processing based on the needs of your background tasks.
The system runs only tasks registered with identifiers on a whitelist of task identifiers. To add the whitelist, add the identifiers to the
Info file (The Info.plist File):
Open the Project navigator and select the desired target.
Click Info and expand Custom iOS Target Properties.
Add a new item to the list and choose “Permitted background task scheduler identifiers,” which corresponds to the
Scheduler Permitted Identifiers
Add the string for each authorized task identifier as a separate item in the array.
Registering, Scheduling, and Running Tasks
During app startup, you register a launch handler, a small block of code that runs the task, and an associated unique identifier for each task. Register all of the tasks before the end of the app launch sequence. For more information, see About the App Launch Sequence.
The following code registers a handler,
handle, that's called when the system runs a task request with the identifier
Submit a task request for the system to launch your app in the background at a later time using
submit(_:). Submitting a task again replaces the previous submission. For example, updating a task's settings requires resubmitting the task.
The code below schedules a refresh task request for the previously registered
com task identifier.
When the system opens your app in the background, it calls the launch handler to run the task.
Your task provides an expiration handler that the system calls if it needs to terminate your task. You also add code to inform the system if the task completes successfully.
Registering and Scheduling Tasks in Extensions
Extensions can schedule a task, such as the update of a machine learning model. Register a task scheduled by extensions in the main app. The system launches the app to run the task.