有谁知道如何迅速解决BackgroundTask问题?

Ali*_*eri 5 swift background-task backgroundtaskidentifier ios12 ios13

将iPad更新到iOS 13后,我在应用程序内部使用后台任务,我的应用程序发出以下消息:

无法结束BackgroundTask:不存在标识符> 13(0xd)的后台任务,或者它可能已经结束。中断UIApplicationEndBackgroundTaskError()进行调试。

我使用UIApplicationEndBackgroundTaskError()进行了调试,但是没有得到任何结果,并且我已经在iOS 12和其他以前的版本上对其进行了测试,它运行良好。

osk*_*rko 0

您需要设置 bgTask = UIBackgroundTaskInvalid

两瞬间

在过期处理程序中。完成你的任务后。

我相信您错过了这两个时刻中的任何一个,这就是您收到该错误的原因。

参见苹果示例代码:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
    // Clean up any unfinished task business by marking where you
    // stopped or ending the task outright.
    [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, preferably in chunks.

    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
});
Run Code Online (Sandbox Code Playgroud)

}