iPhone后台任务在某些时候停止运行

时间:2010-09-16 09:12:32

标签: iphone loops background task

在我的iPhone应用程序中,我有一个后台任务,当应用程序进入后台状态时开始运行。 任务运行正常,结构如下:

运行。 睡5分钟。 跑。 睡5分钟。

出于某种原因,任务在一段时间后停止运行......比如半小时到一小时。

任何人都可以帮我理解为什么吗? 这是后台任务代码:

- (void)applicationDidEnterBackground:(UIApplication *)application {    
NSLog(@"Application entered background state.");

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bgCheckSwitch"] == YES) {

    //UIApplication*    app = [UIApplication sharedApplication];



    // Request permission to run in the background. Provide an

    // expiration handler in case the task runs long.

    NSAssert(bgTask == UIBackgroundTaskInvalid, nil);



    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

        // Synchronize the cleanup call on the main thread in case

        // the task actually finishes at around the same time.

        dispatch_async(dispatch_get_main_queue(), ^{

            if (bgTask != UIBackgroundTaskInvalid)

            {

                [application endBackgroundTask:bgTask];

                bgTask = UIBackgroundTaskInvalid;

            }

        });

    }];



    // Start the long-running task and return immediately.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{



        // Do the work associated with the task.

        [someClass doSomeThing]; //The actual method performed by the task. The looping is in the method.


        dispatch_async(dispatch_get_main_queue(), ^{

            if (bgTask != UIBackgroundTaskInvalid)

            {

                [application endBackgroundTask:bgTask];

                bgTask = UIBackgroundTaskInvalid;

            }

        });

    });


}

}

1 个答案:

答案 0 :(得分:2)

后台任务只运行一段时间,然后操作系统将其杀死。这在多任务WWDC10视频中进行了讨论。