我已经进行了大量的研究,既在Google上也在StackOverflow上。我找到的所有答案都无法在iOS 7中起作用。我开始使用Xcode 5在iOS 7 SDK中编写全新的应用程序。
我想做的就是从应用程序包中的文件播放音频(而不是来自音乐库)。我希望在后台播放音频并在屏幕锁定时进行控制(除了控制中心之外)。
我将APPNAME-Info.plist
键UIBackgroundModes
设置为音频。一切都在ViewController内完成,而不是在应用程序委托中处理。
@interface ViewController : UIViewController <AVAudioPlayerDelegate>
在实现中的viewDidAppear:
方法中,我调用了super,然后是以下代码:
// Once the view has loaded then we can register to begin receiving controls and we can become the first responder
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
在我的实现中的viewWillDisappear:
方法中,我有以下代码:
// End receiving events
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
我还实现了canBecomeFirstResponder
方法,返回值为YES。接下来,我实现了remoteControlReceivedWithEvent:
方法:
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
// If it is a remote control event handle it correctly
if (event.type == UIEventTypeRemoteControl) {
if (event.subtype == UIEventSubtypeRemoteControlPlay) {
[self playPauseAudio:self];
} else if (event.subtype == UIEventSubtypeRemoteControlPause) {
[self playPauseAudio:self];
} else if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {
[self playPauseAudio:self];
}
}
}
让我感到困惑的是,这个完全相同的设置在iOS 6上运作良好。但在iOS 7上却不行。在iOS 6中,它曾经是如此简单。在iOS 7 SDK中有些根本性的改变。我错过了什么?