您的位置:首页 > 其它

【读书笔记】GCD-block-后台运行

2015-07-23 21:19 253 查看
当一个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;
}


参考资料:

http://www.devtang.com/blog/2012/02/22/use-gcd/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: