My application does meet the requirements for using UIBackgroundModes set to ‘App plays audio’. My application plays music from the MPMusicPlayerController iPodMusicPlayer class. What I’m trying to accomplish is to allow the user to set a timer for the music to stop. I’m having an issue with this. I’ve implemented the background task in the applicationDidEnterBackground method as follows:
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
backgroundSupported = device.multitaskingSupported;
}
if (backgroundSupported) {
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:bgTask];
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
if (rootController.sleepTimer != nil)
self.sustainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkTimeRemaining) userInfo:nil repeats:YES];
}
});
});
}
}
with the checkTimeRemaining method:
-(void)checkTimeRemaining{
NSTimeInterval totalSeconds = rootController.timerSetInSeconds.doubleValue;
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:rootController.startDateforSleepTimer];
NSTimeInterval remainingTime = totalSeconds - elapsedTime;
NSLog(@"remaining time %f",remainingTime);
if (remainingTime <= 0) {
[self.musicPlayer pause];
[sustainTimer invalidate];
self.sustainTimer = nil;
}
}
I’m not getting any errors, but the timer doesn’t go beyond the allowed 10 minutes. Since I’m playing audio (along with the Background mode set) I should be able stop the music at the specified time. Any ideas on where I’m going wrong?
Thanks
You can’t get it to work because the audio background modes setting allows audio processing to continue in the background until audio stops. It does not grant any special permissions to the non-audio stuff, such as BackgroundTaskWithExpirationHandler, to continue.
But if you put time logging in an Audio Queue or RemoteIO Audio Unit buffer callback, it will keep getting called as long as audio continues to play.