In this technical blog, we are going to understand how to schedule iOS background tasks. This iOS tutorial is for those who want to implement the background task scheduler in their latest iOS app development project.
What you will learn?
- In this iOS tutorial, you’re going to see an example of using 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 and one of the most important revisions of an Operating System which is being used on more than 1 Billion iOS devices worldwide.
The most significant thing that Apple has brought is the Optimized Trend, which was launched with iOS 12, now making iOS 13 faster & more efficient. The app updating time has been improved, while the app launching time has become 2x quicker. Also, the app download size has been reduced to half (50%).
Let’s talk about some new features and functionalities of iOS 13 and then move on to understand one of the most important functionalities- BackgroundTasks framework.
Here’s a list of some of the important features brought in iOS 13:
- Dark Mode
- Revamped Photos app
- Sign In with Apple (which we already covered in detail with illustration)
- 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 catalog and recognition, Image similarity & classification, On-device speech, Face capture quality, Sentiment classification
- Conversational shortcuts in Siri for apps
- New BackgroundTasks Framework
In this iOS app tutorial, we will talk about the “BackgroundTasks Framework”.
BackgroundTasks Framework
This new framework is used for tasks like cleaning a database, updating a machine learning model, or updating the displayed data for an app, and other deferrable tasks that are better done in the background. It makes efficient use of processing time and power, and run tasks like these when the device is in idle condition.
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.
Our expert iOS developers at Space-O Technologies received a lot of queries from our clients and other developers when BackgroundTasks Framework was introduced. Our developers were happy to help them and decided to come up with a small iOS demo about iOS background image fetching, to explain a few things.
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.
Fetching Image Count While Processing Task In Background
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 and click on “Signing & Capabilities”, then click on “+ Capability”,
4) Double-tap on “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 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.
Let’s Sum Up!
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. We are one of the leading iPhone app development companies and already developed over 2500 iOS apps successfully.
So, if you have an iPhone app idea or want to create a mobile application on the iOS platform with advanced features and functionalities like this one, discuss it with us through our contact form. We are all ears!
Top comments (0)
Some comments have been hidden by the post's author - find out more