我正在开发一个将从 iPod 库中播放音乐的应用程序。我通过 MPMediaPlayerController 从表中检索所选项目并将其传递给详细视图控制器来播放音乐:
MPMediaItem *item = (MPMediaItem *)self.detailItem;
MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:@[item]];
[self.musicPlayer setQueueWithItemCollection:collection];
[self.musicPlayer play];
开始播放音乐。我在 Info.plist 中设置了以下值以启用后台使用:
UIBackgroundModes
>Item 0 - audio
那行得通。当我关闭我的应用程序时,音乐继续播放。所以现在我试图让控制中心的音频控件向我的应用程序发送消息,所以在阅读了一些内容后,我发现我需要做一些事情。所以我创建了一个 UIResponder 的子类并添加了以下几行:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
NSLog(@"CustomApp:remoteControlReceivedWithEvent:%@", event.description);
}
我让我的 AppDelegate 成为自定义 UIResponder 的子类,我有这个:
- (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;
}
和这个
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
现在,我在这里的原因是因为它适用于模拟器而不是设备,我不知道为什么。如果我在模拟器中启动它并调出控制中心并开始按下音频控件,我的自定义 UIResponder 中的 NSLog 会显示在调试器中,但在设备上却没有。实际发生的是播放/暂停按钮什么都不做,然后如果我按下下一个或上一个按钮,它会转到我的 iPod 应用程序上的下一个或上一个曲目并开始播放。
这个等式似乎缺少一些小东西,但我无法弄清楚。我已尽我所能搜索了文档,但找不到与这种情况相关的任何内容,并且有关此特定功能的文档似乎非常有限。