在以前,當應用被按Home鍵退出後,應用僅有最多5秒鐘的時間做一些保存或者清理資源的工作,但是應用可以調用UIApplication的beginBackgroundTaskWithExpirationHandler方法,讓應用最多有10分鐘的時間在後臺長久運行,這個時間可以用來做清理本地緩存、發送統計數據等工作。
讓程序在後臺長久運行的示例代碼如下:
//APPDelegate.h文件
@property (assign ,nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
//APPDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self beginBackgroundUpdateTask];
//在這裏加上你需要長久運行的代碼
[self endBackgroundUptateTask];
}
- (void)beginBackgroundUpdateTask{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUptateTask];
}];
}
- (void)endBackgroundUptateTask{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
_____________來自iOS開發進階(唐巧)