天天看點

iOS應用推到背景繼續執行

@interface AppDelegate : UIResponder <UIApplicationDelegate> {

    __block UIBackgroundTaskIdentifier _bgTask;

}

@property (nonatomic, strong) NSTimer * pushTimer;

@end

在AppDelegate.m中實作

- (void)timerMethod:(NSTimer *)paramSender

{

}

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

    UIDevice * device = [UIDevice currentDevice];

    if([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported])

    {

        self.pushTimer =  [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];

        //向iOS系統,借用10分鐘(預設就是10分鐘)時間。當調用beginBackgroundTaskWithExpirationHandler: 記得必須調用endBackgroundTask:方法,否則iOS會終止你的程式.

        _bgTask = [application beginBackgroundTaskWithExpirationHandler:^

                   {

                       if(_bgTask != UIBackgroundTaskInvalid){

                           [application endBackgroundTask:_bgTask];

                           _bgTask = UIBackgroundTaskInvalid;

                       }

                   }];

        //如果想提前結束10分鐘的背景運作,可在下面加邏輯,目前是空轉.

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            NSInteger remaining = [application backgroundTimeRemaining];

            while (remaining > 30 && _bgTask != UIBackgroundTaskInvalid) {

                sleep(15);

                remaining = [application backgroundTimeRemaining];

                DLog(@"remain %d S", remaining);//iOS 7就隻有180秒,但是超過這個時間程式依然可以運作

            }

        });

    }

}

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

    DLog(@"程式即将進入【前台】");

    if(_bgTask != UIBackgroundTaskInvalid){

        if(_pushTimer!=nil){

            [_pushTimer invalidate];

        }

        [application endBackgroundTask:_bgTask];

        _bgTask = UIBackgroundTaskInvalid;

    }

}

繼續閱讀