当程序进入后台时执行长时间代码

进入后台时,iOS给了我们10分钟的时间做一些事件处理。

AppDelegate.h:

1 #import <UIKit/UIKit.h>
2 
3 @interface AppDelegate : UIResponder <UIApplicationDelegate>
4 
5 @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
6 @property (strong, nonatomic) UIWindow *window;
7 
8 @end

AppDelegate.m修改:

 1 - (void)applicationDidEnterBackground:(UIApplication *)application
 2 {
 3     [self beingBackgroundUpdateTask];
 4     
 5     //需要在后台执行的代码
 6     //...
 7     
 8     [self endBackgroundUpdateTask];
 9 }
10 
11 - (void)beingBackgroundUpdateTask {
12     self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
13         [self endBackgroundUpdateTask];
14     }];
15 }
16 
17 - (void)endBackgroundUpdateTask {
18     [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
19     self.backgroundUpdateTask = UIBackgroundTaskInvalid;
20 }
原文地址:https://www.cnblogs.com/Steak/p/3866342.html