无法接收remoteControlReceivedWithEvent - objective c - ios

时间:2017-05-15 07:23:18

标签: ios objective-c avplayer avaudiosession

我成功启用了我的应用,可以在屏幕锁定后在后台播放音频和视频。但是,为了获得更好的用户体验,我想在锁定的屏幕上显示正在运行的媒体的播放和暂停控制。在线关注几个博客后,添加了以下代码:

@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中添加了背景模式

enter image description here

即使我能够看到控制界面,点击enter image description here按钮时我的应用也不会收到任何用户事件。

我相信我错过了非常明显的事情。任何指针都会有所帮助。

编辑1:iOS - UIEventTypeRemoteControl events not received中接受的答案是您的应用必须是“正在播放”应用。我该怎么做?

1 个答案:

答案 0 :(得分:3)

我找到了问题的答案。我需要在AppDelegate中实现我的问题中的代码来接收事件,而不是在ViewController中实现。