Executing a Finite-Length Task in the Background

Executing a Finite-Length Task in the Background

  Apps that are transitioning to the background can request an extra amount of time to finish any important last-minute tasks. To request background execution time, call the beginBackgroundTaskWithName:expirationHandler: method of the UIApplication class. If your app moves to the background while the task is in progress, or if your app was already in the background, this method delays the suspension of your app. This can be important if your app is performing some important task, such as writing user data to disk or downloading an important file from a network server.

  The way to use the beginBackgroundTaskWithName:expirationHandler: method is to call it before starting the task you want to protect. Every call to this method must be balanced by a corresponding call to the endBackgroundTask: method. Because apps are given only a limited amount of time to finish background tasks, you must call endBackgroundTask: before time expires or the system will terminate your app. You can use the expiration handler you passed to beginBackgroundTaskWithName:expirationHandler: to end the task. (Use the backgroundTimeRemaining property of the app object to see how much time is available.)

 1 // Listing 3-3  Starting a background task at quit time
 2 - (void)applicationDidEnterBackground:(UIApplication *)application
 3 {
 4     bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
 5         // Clean up any unfinished task business by marking where you
 6         // stopped or ending the task outright.
 7         [application endBackgroundTask:bgTask];
 8         bgTask = UIBackgroundTaskInvalid;
 9     }];
10  
11     // Start the long-running task and return immediately.
12     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
13  
14         // Do the work associated with the task, preferably in chunks.
15  
16         [application endBackgroundTask:bgTask];
17         bgTask = UIBackgroundTaskInvalid;
18     });
19 }

 

你可能感兴趣的:(background)