【发布时间】:2017-05-15 07:23:17
【问题描述】:
我成功让我的应用能够在屏幕锁定后在后台播放音频和视频。但是,为了获得更好的用户体验,我想在锁定屏幕上显示正在运行的媒体的播放和暂停控件。在网上关注了几篇博客后,添加了以下代码:
@interface MyControllerClass () <UIGestureRecognizerDelegate, UIApplicationDelegate>
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *activationError = nil;
BOOL success = [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
}
- (void)viewWillDisappear:(BOOL)animated {
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (BOOL) canBecomeFirstResponder {
return YES;
}
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
NSLog(@"received event %@",receivedEvent);
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause: {
if ([self isVideoPlaying]) {
[self.avPlayer pause];
} else {
[self.avPlayer play];
}
break;
}
case UIEventSubtypeRemoteControlPlay: {
[self.avPlayer play];
break;
}
case UIEventSubtypeRemoteControlPause: {
[self.avPlayer pause];
break;
}
default:
break;
}
}
}
在 info.plist 中添加了背景模式
即使我能够看到控制屏幕,我的应用在单击按钮 时也没有收到任何用户事件。
我相信我错过了一些非常明显的东西。任何指针都会有所帮助。
编辑 1:iOS - UIEventTypeRemoteControl events not received 中接受的答案说 您的应用必须是“正在播放”应用。我该怎么做?
【问题讨论】:
标签: ios objective-c avplayer avaudiosession