79

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
raj
  • 805
  • 1
  • 6
  • 7
  • 1
    possible duplicate of [Can't endBackgroundTask: no background task exists with identifier 4, or it may have already been ended](http://stackoverflow.com/questions/17629228/cant-endbackgroundtask-no-background-task-exists-with-identifier-4-or-it-may) – ebi Nov 11 '14 at 22:40

10 Answers10

95

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.

Francesco Ceravolo
  • 1,019
  • 7
  • 5
  • 1
    I'm seeing the same issue. Not sure if this is really an iOS 13 issue or not. Appreciate if you could put your _Single View App_ somewhere to reproduce. thanks. – beshio Oct 15 '19 at 15:05
  • 7
    I started getting the message after I added code that involves notification center and user defaults. I get the message when I leave the app. – hashemi Oct 18 '19 at 20:54
  • 7
    Get the same issue on iOS 13. I'm using background mode for AVAudioPlayer, it is working well on iOS 12. – Zhou Haibo Oct 21 '19 at 16:06
  • 1
    Also my app use AVAudioPlayer in background mode, but this warning is given with an empty new project. @beshio if you want to try open XCode 11, File -> New Project -> Single View App, run and you will find it – Francesco Ceravolo Oct 23 '19 at 12:07
  • 1
    @ChuckZHB did you detect strange crashes like this https://stackoverflow.com/questions/57847960/app-is-getting-crashed-on-app-launch-in-ios-13-beta-version/58359131?noredirect=1#comment103293808_58359131? I've it and I suspect it's a mix of iOS 13 issue and background audio play – Francesco Ceravolo Oct 23 '19 at 12:10
  • 6
    I am getting the same issue on iOS 13. I am using BackgroundTasks framework. I show when my app entered in background. – Gurjinder Singh Oct 23 '19 at 13:12
  • @Francesco Ceravolo I found it may create multi sharedInstance of AVAudioPlayer when using command center control, and I raise a question [https://stackoverflow.com/questions/58515281/mpremotecommandcenter-pause-play-button-create-more-sharedinstance-of-avaudiopla], but I'm not sure if it is related with this issue since I just add command center on iOS 13. – Zhou Haibo Oct 24 '19 at 03:00
  • 1
    I get the same issue when my production app runs on iOS13.x but *not* on iOS12.x. It doesn't cause a crash, but just logs the failure. Unfortunately I can't pinpoint a more accurate cause because I use just about every background service available (location, audio and remote-command centre) – RP-3 Nov 02 '19 at 09:43
  • 1
    I've add a very basic test project on github https://github.com/hons82/Background – Hons Feb 24 '20 at 10:23
  • 1
    Thanks Hons, I've downloaded and tried to run it on an iOS device on 13 and can confirm the error is persisting – Michael Rennison Mar 10 '20 at 15:46
  • I am getting the same issue on iOS 13.3. I can't receive firebase notifications, I also spend a few days to check this issue with no luck – Ahmad Abdullah Apr 06 '20 at 18:39
  • same issue found in ios 13.2.1 – Nalawala Murtuza Oct 07 '20 at 09:44
34

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.

A K M Saleh Sultan
  • 2,403
  • 2
  • 22
  • 28
11

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

iPC
  • 5,916
  • 3
  • 26
  • 38
Julian Osorio
  • 1,116
  • 1
  • 12
  • 30
  • It won't let me do this, it says: Implicit conversion of 'UIBackgroundTaskIdentifier' (aka 'unsigned long') to 'BGAppRefreshTask *' is disallowed with ARC – Jackson Jan 26 '20 at 22:19
6

Reproduced, here is my entire app:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {
        return true
    }
}

And when I take it to background I get the same message. No storyboard or any other noise.

Hans Terje Bakke
  • 1,412
  • 12
  • 14
5

Are you using location update in the background?

If yes, add the below code at the time of getting location authorization from the user - Apple changed the default for allowsBackgroundLocationUpdates to NO from iOS 9 onwards.

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
    locationManager.allowsBackgroundLocationUpdates = YES;
}

Please make sure that you activated the 'Location updates' for background modes under your project 'Signing & Capabilities'. Otherwise it will crash.

A K M Saleh Sultan
  • 2,403
  • 2
  • 22
  • 28
Anand3777
  • 448
  • 2
  • 5
  • 16
3

Using Swift 5 - IOS 13.2.2 - Xcode 11.2 beta 2 (11B44) I managed to get rid of this error by

  • enabling Push notifications in the Capabilities of the app

  • Import the UserNotifications framework

  • then add this code to

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

            // If granted comes true you can enabled features based on authorization.
            guard granted else { return }
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
uplearned.com
  • 3,393
  • 5
  • 44
  • 59
1

Regarding the “Can’t end BackgroundTask: no background task exists with identifier ...” message, as others have said, this can be a red herring, unrelated to what you’re doing.

Regarding your goal of trying to periodically retrieve the user’s location, rather than trying to keep your app running in the background with a timer, you should instead avail yourself of various services for updating the user location in the background, such as the visits location service or the significant change location service. With these services, the OS can wake your app when there is a change in the user’s location.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I get this warning as well and I don't have any background tasks, as far as I know, with my simple note taking app. For example, when a user taps a web url and safari opens, I get the warning. What are some of the red herrings I should be looking for. Or, some resources I can check out to learn more? – Mox Mar 21 '20 at 16:28
  • I don’t know of any exhaustive list, as they are manifold. And when you start using third-party libraries, the situation gets worse. To maintain a list would likely be an exercise in futility. Lol. For me, I generally just search Stack Overflow or a general web search engine for any particular console message, and will often find discussions not unlike this one. You quickly get your arms around which are unrelated to your own code. And for my logging, I use Unified Logging with a `OSLog` with string “category”, which I can then easily filter in the console, separating the wheat from the chaff. – Rob Mar 21 '20 at 16:59
1

I had the same issue and figured out the cause and solution!

Apple has fixed this issue in iOS 13.4 GM though I have workaround for the earlier versions.

While you should embrace using scenes when your app is run under iOS 13 and later, you can fully opt-out while you still support iOS 12 or earlier.

  1. First, completely remove the “Application Scene Manifest” entry from Info.plist.
  2. If there is a scene delegate class, remove it.
  3. If there are any scene related methods in your app delegate, remove those methods.
  4. If missing, add the property var window: UIWindow? to your app delegate.
  5. Your app should now only use the app delegate and under iOS 13 it should have the same life cycle as iOS 12.

Happy coding!

0

I think there is a bug working with xcode 11.2 and the swiftUI framework because I always get the

"Can't end BackgroundTask: no background task exists with identifier..."

message even when my app is not working with background tasks! The good news is that this only stops my app when executing from xcode; use the 'continue program execution' button and the app will be running again.

abanet
  • 1,327
  • 17
  • 22
  • That is not a crash you're talking about, but a breakpoint, when the app stops for debugging. Most probably you've set a breakpoint for ```UIApplicationEndBackgroundTaskError```. – Starsky Feb 04 '20 at 10:32
  • You're right it's not a crash, but I don't have set a breakpoint. – abanet Feb 04 '20 at 10:39
0

This has been fixed in iOS 13.4 GM.

https://developer.apple.com/forums/thread/121990

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30228106) – Emi OB Nov 01 '21 at 12:57