当一个app按home键退出的时候,只有最多5秒的时间做一些保存或清理资源的工作。但是调用beginBackgroundTaskWithExpirationHandler方法,可以最多有10分时间在后台运行。我们可以用这个时间来做清理本地缓存,发送统计数据等事情。
AppDelegate.h

#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; //后台长久运行
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask; @end

AppDelegate.m

//当app进入后台的时候
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self beingBackgroundUpdateTask];
//需要长久运行的代码
[self endBackgroundUpdateTask];
}
#pragma -mark -functions
- (void)beingBackgroundUpdateTask
{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void)endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

参考资料: