仅当iPhone与xcode连接时,后台任务才会运行

时间:2011-07-21 11:16:35

标签: iphone

大家都使用以下代码进行后台任务,当iPhone与xcode连接时,它工作正常,但是当我运行没有连接xcode的应用程序时,后台任务将无法正常工作

- (void)applicationDidEnterBackground:(UIApplication *)application
 {
    back=1.0f;

    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSRunLoop *runLoop=[NSRunLoop currentRunLoop];
    timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeCounter) userInfo:nil repeats:YES];
    [runLoop run];
    [pool release];
 }

请帮助解释为什么会发生这种情况

1 个答案:

答案 0 :(得分:2)

您检查了文档以了解后台执行情况吗?

你应该开始这样的任务:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication*    app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app 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.

        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html