beginBackgroundTaskWithExpirationHandler never gets called

Viewed 20158

I have an app that plays audio in the background. I'm trying to use beginBackgroundTaskWithExpirationHandler to skip to the next track when the current track is finished.

Here is the code that is called when the playback state changes. It never logs the "beginBG called" even though other code in the same method implements successfully in the background.

UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [self ffwButtonPressed:ffwButton];
    NSLog(@"beginBG called");
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

ffwButtonPressed invokes a few different methods to change the track. When that is complete...

UIApplication *app = [UIApplication sharedApplication];
    if (bgTask != UIBackgroundTaskInvalid) {
        [app endBackgroundTask:bgTask]; 
        bgTask = UIBackgroundTaskInvalid;
        NSLog(@"end bgTask");

Edit: Declaration

UIBackgroundTaskIdentifier bgTask;

Edit: In ViewDidLoad

bgTask = 0;
7 Answers

Swift Version:

    var backgroundTask: UIBackgroundTaskIdentifier? = 0
    backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "backgroundTask", expirationHandler: {() -> Void in
        backgroundTask = UIBackgroundTaskInvalid
    })

    // Perform actions in background
    YOUR_CODE_GOES_HERE (e.g. fetch requests, etc.)

    UIApplication.shared.endBackgroundTask(backgroundTask!)

there can be a little modify, we should add endBackgroundTask in expiration handler:

IApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
};

[self ffwButtonPressed:ffwButton];
NSLog(@"beginBG called");
[app endBackgroundTask:bgTask];
Related