Unable to receive remoteControlReceivedWithEvent -

2019-01-26 14:25发布

问题:

I successfully enabled my app to be able to play audio and video in background after the screen is locked. However, for better user experience I want to show play and pause controls of the running media on the locked screen. After following couple of blogs online, added the following code:

@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;
    }
}
}

Added background modes in info.plist

Even though I am able to see the control screen, no user event is received by my app upon clicking the buttons.

I believe I am missing out on something very obvious. Any pointers would be helpful.

EDIT 1: The accepted answer in iOS - UIEventTypeRemoteControl events not received says that Your app must be the “Now Playing” app. How do I do this?

回答1:

I found the answer to my question. I need to implement the code in my question in AppDelegate to receive events instead of implementing in ViewController.