为什么beginBackgroundTaskWithExpirationHandler提前结束?

Pho*_* Le 1 background-process ios ios6 ios7

我试图让这个工作正常,但它总是似乎早在174秒(2.9分钟)结束.我一直在线关注如何使用beginBackgroundTaskWithExpirationHandler的每个教程,我没有看到我的代码有任何问题.我需要这个结束时间为8.5分钟.在调用到期处理程序之前,endBackgroundTask方法甚至不会调用.这有什么不对吗?

- (void)applicationDidEnterBackground:(UIApplication *)application {

        if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
    {
        NSLog(@"Multitasking Supported");

        backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^ {
            NSLog(@"Terminated");

            //Clean up code. Tell the system that we are done.
            [application endBackgroundTask: backgroundTask];
            backgroundTask = UIBackgroundTaskInvalid;
        }];

        timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:self
                                               selector:@selector(count:)
                                               userInfo:nil
                                                repeats:YES];
    }
    else
    {
        NSLog(@"Multitasking Not Supported");
    }

}



-(void)turnOffDesktops:(NSTimer *)time {
//do smth
if(count < (60*8.5)){
    NSLog(@"%d",count);
    count++;
}else{

    [application endBackgroundTask: backgroundTask];
    backgroundTask = UIBackgroundTaskInvalid;

    [timer invalidate];
    timer = nil;
    count = 0;
}
Run Code Online (Sandbox Code Playgroud)

}

Leo*_*ica 5

从来没有Apple承诺允许您执行后台任务多长时间.从历史上看(直到iOS7),应用程序通常在后台运行10分钟.这已不再是这种情况!观看WWDC 2013视频背景.通过添加新的下载和上传API NSURLSession(能够在外部专用守护程序上安排下载和上传任务),Apple大大减少了允许的后台时间.他们这样做是因为这个API一直用于下载和上传,而不是后台的任意任务.

您可以通过查询确定后台剩余的时间- [UIApplication backgroundTimeRemaining].您可以使用它来安排您的代码尽可能快地启动.