beginBackgroundTaskWithExpirationHandler 方法,让应用最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存、发送统计数据等工作。
让程序在后台长久运行的示例代码如下:
//AppDelegate.h 文件
@property (nonatomic , assign) UIBackgroundTaskIdentifier backgroundUpdateTask;
//AppDelegate.m 文件
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self beginBackgroundUpdateTask];
//此处写需要长久运行的代码
[self endBackGroundUpdateTask];
}
- (void)beginBackgroundUpdateTask{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackGroundUpdateTask];
}];
}
- (void)endBackGroundUpdateTask{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}