Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to receive remoteControlReceivedWithEvent - objective c - ios

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

enter image description here

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

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?

like image 336
Astha Gupta Avatar asked Oct 18 '22 12:10

Astha Gupta


1 Answers

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.

like image 112
Astha Gupta Avatar answered Nov 04 '22 20:11

Astha Gupta