Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

12. Multitasking > 12.2. Completing a Long-Running Task in the Background

12.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 all threads paused.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial