美文网首页
iOS程序进入后台后仍可运行定时器

iOS程序进入后台后仍可运行定时器

作者: 逝风不名 | 来源:发表于2017-12-28 09:14 被阅读28次

    网上看到一篇iOS程序进入后台仍可运行定时器的方法,在此做一个记录 原文,也许以后可以用到

    1.在Info.plist中,添加"Required background modes"键,value为:App plays audio

    2.在AppDelegate 的 application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加代码

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.
        NSError *setCategoryErr = nil;
        NSError *activationErr  = nil;
        [[AVAudioSession sharedInstance]
         setCategory: AVAudioSessionCategoryPlayback
         error: &setCategoryErr];
        [[AVAudioSession sharedInstance]
         setActive: YES
         error: &activationErr];
        self.window.backgroundColor = [UIColor whiteColor];
        [self.window makeKeyAndVisible];    return YES;
    }
    

    3在AppDelegate进入后台的方法applicationDidEnterBackground:(UIApplication *)application添加代码

    - (void)applicationDidEnterBackground:(UIApplication *)application{
        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;
                }
            });
        });
    }
    

    相关文章

      网友评论

          本文标题:iOS程序进入后台后仍可运行定时器

          本文链接:https://www.haomeiwen.com/subject/nbgcdxtx.html