beginBackgroundTaskWithExpirationHandler never gets called

20,082

Solution 1

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

Solution 2

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

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  
Share:
20,082
mnort9
Author by

mnort9

Updated on July 30, 2022

Comments

  • mnort9
    mnort9 almost 2 years

    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;