How to Update App Content With Background Tasks Using The Task Scheduler In iOS 13?
More efficiently manage your tasks in i0S13.
Join the DZone community and get the full member experience.
Join For FreeIn this iOS tutorial, you’re going to see an example of how to use the new BackgroundTasks framework for fetching images in the background while the phone is in idle mode.
Last month at WWDC Developer Conference 2019, Apple released the latest iOS 13 with a huge list of new features and functionalities. It was the second major revisions of the OS. It is now being used on more than one billion iOS devices worldwide.
The most significant thing that Apple has made in this update is Optimized Trend. Originally launched in iOS 12, Optimized Trend has made iOS 13 faster and more efficient. The app updating time has been improved, while the app launching time has become two times as fast when compared to the previous iteration. The app download size has also been reduced to half.
Here’s a list of some of the important features brought in iOS 13:
- Dark Mode.
- Revamped Photos app.
- Sign In with Apple.
- HomeKit Secure Video.
- Name and image in Messages.
- Swiping keyboard.
- Multi-user HomePod.
- All-new Reminders app.
- Memoji and stickers.
- Smarter, smoother Siri voice assistance.
In terms of technical functionalities, Apple has introduced:
- Advances in contextual action menus in iOS, macOS, and iPadOS.
- UIWindowScene API and multitasking in iPadOS.
- AI/ML functionalities like image and speech saliency, word embeddings, sound analysis, text catalogue and recognition, image similarity and classification, on-device speech, Face capture quality, sentiment classification.
- Conversational shortcuts in Siri for apps.
- New BackgroundTasks Framework.
BackgroundTasks Framework
This new framework is used for deferrable tasks that are better done in the background such as cleaning a database, updating a machine learning model, updating the displayed data for an app. This makes efficient use of processing time and power.
BackgroundTasks Framework has two main task requests under BGTaskScheduler:
- BGAppRefreshTaskRequest: This is a request to launch an app in the background to execute a short refresh task.
- BGProcessingTaskRequest: This is a request to launch an app in the background and execute a process that takes a longer time to complete.
BackgroundTasks can be used to perform various activities like database cleaning, uploading pictures to a server, syncing pictures in other devices, and many more.
In this iOS tutorial, we are going to take the iOS background task example of fetching the latest count of added images in the image gallery.
Implementing BackgroundTasks Framework in Your Project
1. Create a new project using XCODE 11.
2. Select “Single View App” in the iOS section and enter the project name. (We have kept the project name as “SOBackgroundTask”.)
3. Go to SoBackgroundTask Target, click on “Signing & Capabilities”, and then click on “+ Capability”.
4. Double-tap “Background Modes”.
5. Select “Background Fetch” and “Background Processing” from all background tasks.
6. Add “BGTaskSchedulerPermittedIdentifiers” key in info.plist and add a task identifier array.
Note: The system only runs the tasks registered with identifiers on a whitelist of task identifiers.
7. Import BackgroundTasks in AppDelegate.swift.
8. Create registerBackgroundTaks() method with identifier (use the same identifier we used in info.plist) and call it from Application:didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
registerBackgroundTaks()
return true
}
//MARK: Register BackGround Tasks
private func registerBackgroundTaks() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.SO.imagefetcher", using: nil) { task in
//This task is cast with processing request (BGProcessingTask)
self.scheduleLocalNotification()
self.handleImageFetcherTask(task: task as! BGProcessingTask)
}
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.SO.apprefresh", using: nil) { task in
//This task is cast with processing request (BGAppRefreshTask)
self.scheduleLocalNotification()
self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
}
}
9. Create scheduleImagefetcher() and scheduleAppRefresh() method for fetching images from the gallery and refresh app once image fetch is completed. These methods are called from applicationDidEnterBackground.
func applicationDidEnterBackground(_ application: UIApplication) {
scheduleAppRefresh()
scheduleImagefetcher()
}
func scheduleImagefetcher() {
let request = BGProcessingTaskRequest(identifier: "com.SO.imagefetcher")
request.requiresNetworkConnectivity = false // Need to true if your task need to network process. Defaults to false.
request.requiresExternalPower = false
//If we keep requiredExternalPower = true then it required device is connected to external power.
request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60) // fetch Image Count after 1 minute.
//Note :: EarliestBeginDate should not be set to too far into the future.
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule image fetch: \(error)")
}
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.SO.apprefresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 2 * 60) // App Refresh after 2 minute.
//Note :: EarliestBeginDate should not be set to too far into the future.
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
Note: You need to cancel pending background tasks if any, otherwise it will display error code=2.
To cancel the pending background task, we call the below method before scheduling a new task.
func cancelAllPendingBGTask() {
BGTaskScheduler.shared.cancelAllTaskRequests()
}
Note: iOS background task time limit is 30 seconds; the policy is still the same.
Conclusion
We hope this iOS tutorial has helped you to understand how BackgroundTasks Framework works. You can get the source code by referring to the github demo.
Here, we took only one example of fetching images in the background, there are various tasks for which we can use this framework.
Let us know if you have any suggestions or queries in this tutorial or any questions regarding iPhone app development.
Opinions expressed by DZone contributors are their own.
Comments