iOS7 Programming Cookbook 第十六章学习笔记 发表于 2014-06-02 | 分类于 NSTimer , UIBackgroundTaskIdentifier , NSTimeInterval , scheduledTimerWithTimeInterval | 阅读次数: 字数统计: 379 字 | 阅读时长 ≈ 2 分钟 ####Completing a Long-Running Task in the Background 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#import "AppDelegate.h"@interface AppDelegate ()//UIBackgroundTaskIdentifier : 一个独特的标志,这个标志标识请求在后台运行@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;@property (nonatomic, strong) NSTimer *myTimer;@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES;}//结束后台任务- (void)endBackgroundTask{ dispatch_queue_t mainQueue = dispatch_get_main_queue(); __weak AppDelegate *weakSelf = self; dispatch_async(mainQueue, ^(void) { AppDelegate *strongSelf = weakSelf; if (strongSelf != nil){ //时间停止计时 [strongSelf.myTimer invalidate]; [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier]; //这个常数应该用于初始化变量或检查错误。 strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } }); }//一个布尔值表示是否支持多任务当前的设备上。(只读)- (BOOL)isMultitaskingSupported{ BOOL result = NO; if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]){ result = [[UIDevice currentDevice] isMultitaskingSupported]; } return result; }- (void)timerMethod:(NSTimer *)paramSender{ NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining]; if (backgroundTimeRemaining == DBL_MAX){ NSLog(@"背景剩余时间=待定"); } else { NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining); } }//应用程序已经在后台- (void)applicationDidEnterBackground:(UIApplication *)application{ if ([self isMultitaskingSupported] == NO){ return; } //添加方法 self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES]; //标志着一个新的开始长时间运行的后台任务。 self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) { [self endBackgroundTask]; }]; }//应用程序即将进入前景- (void)applicationWillEnterForeground:(UIApplication *)application{ if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){ [self endBackgroundTask]; } }@end Reference O’Reilly Shop iOS 7 Programming Cookbook 坚持原创技术分享,您的支持将鼓励我继续创作! 打赏 支付宝