在以前,當應用被按Home鍵退出後,應用僅有5秒鐘的時間做一些保存或清理資源的工作。但是應用可以調用UIApplication的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;
}