大家都使用以下代码进行后台任务,当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];
}
请帮助解释为什么会发生这种情况
答案 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;
});
}