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;
}
本文介绍了如何利用beginBackgroundTaskWithExpirationHandler方法使iOS应用在后台最多获得10分钟的额外运行时间,以执行如清理缓存、发送统计数据等任务。提供了一个示例代码,展示了在AppDelegate中实现后台任务的开始和结束方法。
964

被折叠的 条评论
为什么被折叠?



