I am working on an app that will be playing music from the iPod library. I am playing the music via MPMediaPlayerController by retrieving the selected item from a table and passing it to a detail view controller:
MPMediaItem *item = (MPMediaItem *)self.detailItem;
MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:@[item]];
[self.musicPlayer setQueueWithItemCollection:collection];
[self.musicPlayer play];
Which starts playing the music. I have set the following values in my Info.plist to enable background use:
UIBackgroundModes
>Item 0 - audio
And that works. When I close my app the music keeps playing. So now I am trying to get the audio controls in the control center to send messages to my app so after some reading I found that I needed to do a few things. So I created a subclass of UIResponder and added the following lines:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
NSLog(@"CustomApp:remoteControlReceivedWithEvent:%@", event.description);
}
I made my AppDelegate a subclass of the custom UIResponder where I have this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[MainWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.mainViewController = [[BrowserViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:self.mainViewController];
self.window.rootViewController = navigationController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
return YES;
}
and this
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
Now, my the reason why I am here is because this works in the simulator but not the device and I can't figure out why. If I launch this in the simulator and bring up the control center and start pressing the audio controls the NSLog in my custom UIResponder shows in the debugger but on the device it doesn't. What actually happens is that the play/pause button does nothing, then if I press the next or previous button it goes to the next or previous track on my iPod app and starts playing that.
It seems like there is something small missing from this equation but I cannot figure it out. I have searched the documentation as best as I can but can't find anything related to this situation and the documentation on this particular functionality seems quite limited.
Try this code in
viewDidLoad()
with Danilo's answer