beginBackgroundTaskWithExpirationHandler never gets called

mnort9 picture mnort9 · Jul 23, 2012 · Viewed 19.8k times · Source

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;

Answer

Tomusm picture Tomusm · Jul 25, 2012

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