Search code examples
iphoneobjective-ciosbackground-processuiapplication

beginBackgroundTaskWithExpirationHandler never gets called


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;

Solution

  • You are actually misunderstanding the function -(UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler

    The block argument called "handler" is what will happen when the background task expire (10min).

    To get your code running you need to put your code out of the expiration handler:

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

    Here is a link to the documentation