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

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

UIBackgroundTaskIdentifier bgTask;

in the header file, and initialized as:

bgTask = UIBackgroundTaskInvalid;

But still, I am getting this message in the gdb:

Can't endBackgroundTask: no background task exists with identifier 23dc, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.

Why? And how can I solve this?


Solution 1:

I lose many days looking for the piece of code or framework that was causing this warning in the debug console Can't end BackgroundTask: no background task exists with identifier 2 (0x2), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.

Finally I've created an empty project Single View App. Only code generated by Xcode, I run the app on simulator, put it in background and I see the same warning. So I can say it's an iOS 13 issue. I hope Apple will fix it quickly because in Crashlytics I found some crash in my app caused by it.

Solution 2:

In Xcode, switch to the breakpoint navigator (View > Navigators > Show Breakpoint Navigator) then push the + button in the bottom left and select Add Symbolic Breakpoint and enter “UIApplicationEndBackgroundTaskError” as the symbol.

Solution 3:

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