Threads and App Backgrounding

When your app is backgrounded and suspended (Chapter 11), a problem arises if your code is running. The system doesn’t want to kill your code while it’s executing; on the other hand, some other app may need to be given the bulk of the device’s resources now. So as your app goes into the background, the system waits a short time for your app to finish doing whatever it may be doing, but it then suspends your app and stops it by force.

This shouldn’t be a problem from your main thread’s point of view, because your app shouldn’t have any time-consuming code on the main thread in the first place; you now know that you can avoid this by using a background thread. On the other hand, it could be a problem for lengthy background operations, including asynchronous tasks performed by the frameworks. You can request time to complete a lengthy task (or at least abort it yourself, coherently) in case your app is backgrounded, by wrapping it in calls to UIApplication’s beginBackgroundTaskWithExpirationHandler: and endBackgroundTask:.

You call beginBackgroundTaskWithExpirationHandler: to announce that a lengthy task is beginning; it returns an identification number. At the end of your lengthy task, you call endBackgroundTask:, passing in that same identification number. This tells the application that your lengthy task is over and that, if your app has been backgrounded while the task was in progress, it is now okay to suspend you.

The argument to beginBackgroundTaskWithExpirationHandler: ...

Get Programming iOS 4 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.