码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2017-08-05 09:50:26      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:lin   tle   pac   ora   hex   handler   post   mic   分享   

当一个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/

 


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

标签:lin   tle   pac   ora   hex   handler   post   mic   分享   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/7288882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!