[IOS 开发] 无限后台运行

来源:互联网 发布:淘宝商城宠物狗 编辑:程序博客网 时间:2024/06/08 12:47


@implementation AppDelegate{    NSTimer* _timer;}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {        // Override point for customization after application launch.    return YES;}- (void)applicationWillResignActive:(UIApplication *)application {    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}-(void)logAction{    NSLog(@"1");}- (void)applicationDidEnterBackground:(UIApplication *)application{    _timer =  [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(logAction) userInfo:nil repeats:YES];        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];        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;            }        });    });}- (void)applicationWillEnterForeground:(UIApplication *)application {    [_timer setFireDate:[NSDate distantFuture]];    // 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.}


0 0
原创粉丝点击