Cover by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

14.2. Completing a Long-Running Task in the Background

Problem

You want to borrow some time from iOS to complete a long-running task when your application is being sent to the background.

Solution

Use the beginBackgroundTaskWithExpirationHandler: instance method of UIApplication. After you have finished the task, call the endBackgroundTask: instance method of UIApplication.

Discussion

When an iOS application is sent to the background, its main thread is paused. The threads you create within your application using the detachNewThreadSelector:toTarget:withObject: class method of NSThread are also suspended. If you are attempting to finish a long-running task when your application is being sent to the background, you must call the beginBackgroundTaskWithExpirationHandler: instance method of UIApplication to borrow some time from iOS. The backgroundTimeRemaining property of UIApplication contains the number of seconds the application has to finish its job. If the application doesn’t finish the long-running task before this time expires, iOS will terminate the application. Every call to the beginBackgroundTaskWithExpirationHandler: method must have a corresponding call to endBackgroundTask: (another instance method of UIApplication). In other words, if you ask for more time from iOS to complete a task, you must tell iOS when you are done with that task. Once this is done and no more tasks are requested to be running in the background, your application will be fully put into the background ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required