我的问题是 - 当音频在我的iPad后台播放时,"我的应用程序图标"不会出现。我正在使用iPodMusicPlayer。为了在后台播放音频,我编写了这些代码。
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated
{
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
iPod 控件将在应用程序处于后台时发送这些事件
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
[self performSelector:@selector(playPause:)];
break;
case UIEventSubtypeRemoteControlPreviousTrack:
//[self previousSong:nil];
//[self performSelector:@selector(previousSong:)];
break;
case UIEventSubtypeRemoteControlNextTrack:
//[self performSelector:@selector(nextSong:)];
break;
default:
break;
}
}
}
和 info.plist 我还设置了"所需的背景模式"
还必须将UIBackgroundModes
添加到Info.plist
中,并将其值设置为 audio
。
请查看 iOS 应用程序编程指南,特别是应用程序状态和多任务处理部分,了解有关如何在后台执行任务的详细信息。
[更新]
还要将这两行添加到AppDelegate.m
中的application:didFinishLaunchingWithOptions:
:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
当您开始播放音频时,此代码:
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
[_player play];
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
这应该可以做到。在模拟器和设备上进行测试。