IOS开发模块总结(二)后台运行程序(2)Task completion-UIBackgroundTaskIdentifier

来源:互联网 发布:encore制谱软件 编辑:程序博客网 时间:2024/05/20 11:25

通过UIBackgroundTaskIdentifier可以实现有限时间内在后台运行程序

程序进入后台时调用applicationDidEnterBackground函数,

首先判断设置是否支付后台运行

通过beginBackgroundTaskWithExpirationHandler获取UIBackgroundTaskIdentifier

后就可以在后台获取一定的时间去指行我们的代码,可以通过

NSTimeInterval backgroundTimeRemanging = [[UIApplicationsharedApplication] backgroundTimeRemaining];

NSLog(@"backgroundTimeRemanging = %.02f", backgroundTimeRemanging);

来查看后台可以执行的时间,注意,在beginBackgroundTaskWithExpirationHandler代码块中一定要

调用UIApplicationendBackgroundTask:方法来结束后台任务 如

[app endBackgroundTask:_bgTask];

这里的_bgTask是通过beginBackgroundTaskWithExpirationHandler得到的.要保持一致。

最后,当我们的应用回到前台,如果我们的后台任务还在执行中,我们需要确保我们在干掉它: 

- (void)applicationWillEnterForeground:(UIApplication *)application{ 

if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){ 

[self endBackgroundTask]; } 

@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) ViewController *viewController;@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;@property (nonatomic, strong) NSTimer * myTimer;- (BOOL)isMutiltaskingSupported;@end// 判断当前设备是否支持 后台多任务- (BOOL)isMutiltaskingSupported{    BOOL result = NO;    if ( [[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {        result = [[UIDevice currentDevice] isMultitaskingSupported];    }    return result;}// 定时器调用方法- (void)timerMethod:(NSTimer *)paramSender{    NSTimeInterval backgroundTimeRemanging = [[UIApplication sharedApplication] backgroundTimeRemaining];    if ( backgroundTimeRemanging == DBL_MAX) {        NSLog(@"Background Time Remaining = Undeterminded");    }    //--显示后台任务还剩余的时间    NSLog(@"Background Timer Remaining = %.02f Seconds", backgroundTimeRemanging);}// 进入挂起状态时候,调用方法- (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.    if ( [self isMutiltaskingSupported] == NO) {        NSLog(@"---> 不支持后台多任务");        return;    }        self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{        [self endBackgroundTask];    }];<pre name="code" class="objc">    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f                                                    target:self                                                  selector:@selector(timerMethod:)                                                  userInfo:nil                                                   repeats:YES];    
}// 任务完成,处理释放对象- (void)endBackgroundTask{    dispatch_queue_t mainQueue = dispatch_get_main_queue();    __weak AppDelegate *weakSelf = self;    dispatch_async(mainQueue, ^{        AppDelegate * strongSelf = weakSelf;        if ( strongSelf != nil) {            [strongSelf.myTimer invalidate];            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];            strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;        }    });}
- (void)applicationWillEnterForeground:(UIApplication *)application{ if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){ [self endBackgroundTask]; } } 






0 0