Article

Extending Your App's Background Execution Time

Ensure that critical tasks finish when your app moves to the background.

Overview

Extending your app’s background execution time ensures that you have adequate time to perform critical tasks. When your app moves to the background, the system calls your app delegate’s applicationDidEnterBackground(_:) method. That method has five seconds to perform any tasks and return. Shortly after that method returns, the system puts your app into the suspended state. For most apps, five seconds is enough to perform any crucial tasks, but if you need more time, you can ask UIKit to extend your app’s runtime.

You extend your app’s runtime by calling the beginBackgroundTask(withName:expirationHandler:) method. Calling this method gives you extra time to perform important tasks. (Find out how much time remains using the backgroundTimeRemaining property.) When you finish your tasks, call the endBackgroundTask(_:) method right away to let the system know that you are done. If you do not end your tasks in a timely manner, the system terminates your app.

Listing 1 shows an example that configures a background task so that the app may save data to its server, which could take longer than five seconds. The beginBackgroundTask(withName:expirationHandler:) method returns an identifier that you must save and pass to the endBackgroundTask(_:) method.

Listing 1

Extending the app's background execution time

func sendDataToServer( data : NSData ) {
   // Perform the task on a background queue.
   DispatchQueue.global().async {
      // Request the task assertion and save the ID.
      self.backgroundTaskID = UIApplication.shared.
                 beginBackgroundTask (withName: "Finish Network Tasks") {
         // End the task if time expires.
         UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
         self.backgroundTaskID = UIBackgroundTaskInvalid
      }
            
      // Send the data synchronously.
      self.sendAppDataToServer( data: data)
            
      // End the task assertion.
      UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
      self.backgroundTaskID = UIBackgroundTaskInvalid
   }
}

See Also

Background Execution

Updating Your App with Background App Refresh

Fetch content opportunistically in the background and update your app's interface.

About the Background Execution Sequence

Learn the order in which your custom code is executed when your app moves to the background.