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 ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.