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;
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
I ended up not needing beginBackgroundTaskWithExpirationHandler
at all. This line solved my problem...
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With