Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 683
mnort9 Avatar asked Jul 23 '12 17:07

mnort9


2 Answers

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

like image 133
Tomusm Avatar answered Nov 20 '22 23:11

Tomusm


I ended up not needing beginBackgroundTaskWithExpirationHandler at all. This line solved my problem...

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  
like image 37
mnort9 Avatar answered Nov 20 '22 22:11

mnort9