2017-05-15 64 views
5

我成功啓用了我的應用程序,以便能夠在屏幕鎖定後在後臺播放音頻和視頻。但是,爲了獲得更好的用戶體驗,我希望在鎖定的屏幕上顯示播放和暫停正在運行的媒體的控件。在線下的情侶博客後,添加以下代碼:在info.plist中無法接收remoteControlReceivedWithEvent - 目標c - ios

enter image description here

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

增加的背景模式,即使我能看到的控制屏幕,沒有用戶事件通過點擊按鈕enter image description here我的應用程序收到。

我相信我錯過了非常明顯的事情。任何指針都會有幫助。

編輯1:在iOS - UIEventTypeRemoteControl events not received接受的答案說,您的應用程序必須是「正在播放」的應用程序。我該怎麼做?

回答

2

我找到了我的問題的答案。我需要在AppDelegate中實現上面的代碼來接收事件,而不是在ViewController中實現。