Home / IOS Development / How to use iOS background task to keep the app up to date? (Training)

How to use iOS background task to keep the app up to date? (Training)

In this technical blog, we understand how to plan iOS background tasks. This iOS guide is for those who want to implement the background task planner in their latest iOS app development project.

What are you learning?

  • In this guide iOS, see an example of using the new BackgroundTask's framework to retrieve images in the background while the phone is in sleep mode.

Last month at the WWDC Developer Conference 2019, Apple released the latest iOS 13 with a large list of new features and features. It was the second major and one of the most important audits of an operating system used on more than 1 billion iOS devices worldwide.

The most significant thing Apple has brought is the optimized trend, launched with iOS 1

2, making iOS 13 faster and more efficient. The app update time has improved while the app's start time has been 2 times faster. The app download size is also reduced to half (50%).

Let's talk about some new features and functionalities in IOS 13, and then continue to understand one of the key features BackgroundTasks Framework ].

Here is a list of some of the important features of iOS 13:

  • Dark Mode
  • Revamped Photos app
  • Sign in with Apple (as we already covered in detail with illustration)
  • HomeKit Secure Video
  • Name and picture in Messages
  • Swiping keyboard
  • Multi-user HomePod
  • All-new Reminders app
  • Memoji and stickers
  • Smarter, smoother Siri Voice Assistance

In Terms of Technical Features Apple Has Introduced:

  • Advances in Contextual Action Menus in IOS, MacOS, and iPadOS
  • UIWindowScene API and Multitasking in iPadOS
  • AI / ML Features such as Image and Speech saliency, Word embeddings, Sound analysis, Text directory and recognition, image similarity and classification, speech on the device, face quality, sentiment classification
  • Conversation shortcuts in Siri for apps
  • New BackgroundTasks Framework

In this guide iOS app we'll talk about " [ BackgroundTasks Framework


BackgroundTasks Framework

This new framework is used for tasks such as clearing a database, updating a machine learning model, or updating the displayed data for an app and other scalable tasks that are better done in the background.

BackgroundTasks Framework has two main task requests under BGTaskScheduler:

  1. BGAppRefreshTaskRequest : This is a request to launch an app in the background to perform a short update task.
  2. BGProcessingTaskRequest : This is a request to start an app in the background and perform a process that takes longer to complete.

BackgroundTasks can be used to perform various activities such as database management, uploading images to a server, synchronizing images in other devices and many more.

Our experts iOS developers at Space-O Technologies received many questions from our customers and other developers as the BackgroundTasks Framework was introduced. Our developers were happy to help them and decided to come up with a small iOS demo about downloading the iOS wallpaper to explain a few things.

In this tutorial iOS, we will take the iOS background example to retrieve the last count of added images in the image gallery.

Retrieve the image number while processing the task in the background

Implementing the BackgroundTasks Framework in your project

1. Create a new project using XCODE 11.

 Create a new project

2. Select "Single View App" in the iOS section and enter the project name. ” width=”625″ height=”335″ srcset=”https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150714/SS2-1024×549.png 1024w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150714/SS2-300×161.png 300w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150714/SS2-624×335.png 624w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150714/SS2.png 1395w” sizes=”(max-width: 625px) 100vw, 625px”/>

  project name

  project properties

project properties ” width=”625″ height=”287″ srcset=”https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150718/SS3-1024×470.png 1024w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150718/SS3-300×138.png 300w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150718/SS3-624×286.png 624w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150718/SS3.png 1405w” sizes=”(max-width: 625px) 100vw, 625px”/>

3. Go to SoBackgroundTask Target and click "Signing & Capabilities" and then click "+ Capability",

adjust capabilities ” width=”625″ height=”118″ srcset=”” data-srcset=”https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150720/SS4-1024×194.png 1024w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150720/SS4-300×57.png 300w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150720/SS4-624×118.png 624w, https://d3l69s690g8302.cloudfront.net/wp-content/uploads/2019/07/13150720/SS4.png 1402w” sizes=”(max-width: 625px) 100vw, 625px”/>

4. Double-click "Background Mode"

 specify background modes

5. Select "Background retrieval" and "Background processing" from all background tasks.

 specify background modes

6. Add the "BGTaskSchedulerPermittedIdentifiers" key in the info.plist and add a task identifier group.

 Add Task Identifier

Note: The system only runs the tasks registered with identifiers on a task list identifiers.

7. import backgrounds in AppDelegate.swift.

8. Create registryBackgroundTaks () 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 registryBackgroundTaks () {

BGTaskScheduler.shared.register (forTaskWithIdentifier: "com.SO.imagefetcher", uses: null) {task in
// This task is thrown with a treatment request (BGProcessingTask)
self.scheduleLocalNotification ()
self.handleImageFetcherTask (task: task like! BGProcessingTask)

BGTaskScheduler.shared.register (forTaskWithIdentifier: "com.SO.apprefresh", uses: null) {task in
// This task is thrown with a treatment request (BGAppRefreshTask)
self.scheduleLocalNotification ()
self.handleAppRefreshTask (task: task like! BGAppRefreshTask)

9. Create the scheduleImagefetcher () and scheduleAppRefresh () method to retrieve images from the gallery and update the app when image retrieval is complete. These methods are called from the applicationDidEnterBackground.

  func applicationDidEnterBackground (_ application: UIApplication) {
scheduleAppRefresh ()
scheduleImage fetcher ()

func scheduleImagefetcher () {
la request = BGProcessingTaskRequest (identify: "com.SO.imagefetcher")
request.requiresNetworkConnectivity = false // Need to threaten if your task requires networking. The default is false.
request.requiresExternalPower = false
// If we keep requiredExternalPower = true then it is necessary that the device is connected to external power.

request.earliestBeginDate = Date (timeIntervalSinceNow: 1 * 60) // retrieve image count after 1 minute.
// Note :: EarliestBeginDate should not be set too far into the future.
do {
try BGTaskScheduler.shared.submit (request)
} catch {
print ("Could not schedule image retrieval: (error)")

func scheduleAppRefresh () {
la request = BGAppRefreshTaskRequest (ID: "com.SO.apprefresh")
request.earliestBeginDate = Date (timeIntervalSinceNow: 2 * 60) // App update after 2 minutes.
// Note :: EarliestBeginDate should not be set too far into the future.
do {
try BGTaskScheduler.shared.submit (request)
} catch {
print ("Could not schedule app update: (error)")

Note: You must cancel pending background tasks if anything, otherwise it will display error code = 2.

To cancel pending background task, we call the procedure below before planning 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 it up!

We hope this iOS tutorial has helped you understand how the BackgroundTasks Framework works. You can get the source code by going to the gitfhub link.

Here we just took one example of getting pictures in the background. There are various tasks that we can use this framework program.

Please let us know if you have any suggestions or questions in this tutorial or questions about iPhone app development. We are one of the leading iPhone development companies and have already developed over 2500 iOS apps.

So if you have an iPhone app or want to create a mobile application on the iOS platform with advanced features and features like this one, discuss it with us through our contact form. We are all ears!

This page was last edited on July 13, 2019, at 15:35.

Do you have an idea?

Get your free consultation now

Source link