selector

定时器后台运行

2018-12-05  本文已影响0人  温水煮青蛙a

定时器的代码正常写 在app后台运行的时候 定时器的方法就会正常呗调用

#import <AVFoundation/AVFoundation.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/*定时器后台运行*/
    NSError *setCategoryErr = nil;
    NSError *activationErr = nil;
    /*设置Audio Session的Category 一般会在激活之前设置好Category和mode。但是也可以在已激活的audio session中设置,不过会在发生route change之后才会发生改变*/
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    /*激活Audio Session*/
    [[AVAudioSession sharedInstance] setActive:YES error: &activationErr];
}
- (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.
    NSLog(@"后台状态 → 挂起状态");
    
    UIApplication *app = [UIApplication sharedApplication];
    __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;
            }
        });
    });
}
上一篇 下一篇

猜你喜欢

热点阅读