iOS-OC-APP后台持续运行

来源:互联网 发布:怎样成为淘宝直播 编辑:程序博客网 时间:2024/04/27 15:55

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


0 0
原创粉丝点击