16.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access