iOS WorkManager is a wrapper around BackgroundTasks
Currently only proccesing tasks are supported
It is useful to run periodic tasks, such as fetching remote data on a regular basis.
Before you can schedule a background task, you must register each task with a unique identifier in your project's Info.plist
:
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>be.vrt.ios-workmanager.oneoffbackgroundtask</string>
<string>be.vrt.ios-workmanager.recurringbackgroundtask</string>
</array>
Also add required UIBackgroundModes:
<key>UIBackgroundModes</key>
<array>
<string>processing</string>
</array>
Register a task inside your AppDelegate
didFinishLaunchingWithOptions
and provide a callback for when the task is executed:
WorkManager.shared.registerTask(withIdentifier: "be.vrt.ios-workmanager.oneoffbackgroundtask") { task in
self.handleOneOffTrigger(task: task as! BGProcessingTask)
}
Two kinds of background tasks can be registered :
- One off task : runs only once
- Periodic tasks : runs indefinitely on a regular basis
To schedule a one off task:
WorkManager.shared.scheduleOneOffTask(withIdentifier: "be.vrt.ios-workmanager.oneoffbackgroundtask", name: "update_something")
To schedule a periodic task:
WorkManager.shared.schedulePeriodicTask(withIdentifier: "be.vrt.ios-workmanager.recurringbackgroundtask", name: "update_something", frequency: 900)
Indicates how along a task should wait before its first run.
WorkManager.shared.schedulePeriodicTask(withIdentifier: "be.vrt.ios-workmanager.recurringbackgroundtask", name: "update_something", frequency: 900, initialDelay: 900)
Indicates the desired behaviour when the same task is scheduled more than once.
The default is KEEP
WorkManager.shared.scheduleOneOffTask(withIdentifier: "be.vrt.ios-workmanager.oneoffbackgroundtask", name: "update_something", existingWorkPolicy: .replace)
WorkManager.shared.schedulePeriodicTask(withIdentifier: "be.vrt.ios-workmanager.recurringbackgroundtask", name: "update_something", frequency: 900, constraints: [.requiresExternalPower, .requiresNetworkConnectivity])
Indicates the waiting strategy upon task failure.
You can also specify the delay.
WorkManager.shared.schedulePeriodicTask(withIdentifier: "be.vrt.ios-workmanager.recurringbackgroundtask", name: "update_something", frequency: 900,backoffPolicy: .exponential, backoffPolicyDelay: 500)
A task can be cancelled in different ways :
WorkManager.shared.cancelTask(withIdentifier identifier: "")
WorkManager.shared.cancelTask(withTag tag: "")
WorkManager.shared.cancelAllTasks()
See example project