Can't endBackgroundTask: no background task exists with identifier, or it may have already been ended

前端 未结 9 840
时光说笑
时光说笑 2020-11-27 02:42

I am using background task to run the timer in the background to update the user\'s location. It\'s declared as:

UIBackgroundTaskIdentifier bgTask;
         


        
9条回答
  •  鱼传尺愫
    2020-11-27 03:08

    You need to set bgTask = UIBackgroundTaskInvalid

    in two moments

    1. In the expiration handler.
    2. After finishing your task.

    I believe you are missing any of those two moments and that is why you are getting that error.

    See apple example code:

    - (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;
        });
    }
    

    link: https://developer.apple.com/documentation/backgroundtasks/bgtask?language=objc

提交回复
热议问题