iOS-OC-APP後臺持續執行

ZFJ_張福傑發表於2016-01-25

//1.設定定時器
@implementation AppDelegate
{
    NSTimer* _timer;
}
//2.app進入後臺  啟動定時器
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [_timersetFireDate:[NSDatedistantFuture]];
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
//3.後臺執行函式
-(void)logAction
{
    NSLog(@"在後臺執行");
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    _timer =  [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:selfselector:@selector(logAction)userInfo:nilrepeats:YES];
    [[NSRunLoopcurrentRunLoop] addTimer:_timerforMode:NSDefaultRunLoopMode];
    UIApplication*   app = [UIApplicationsharedApplication];
    __block   UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid){
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid){
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });

    // 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.
}


相關文章