Play / Pause calls when using MPRemoteCommandCenter

I am creating a music player application and everything is working fine. I still use the system music player, but now I want to switch to using the music player of the application, as well as where I ran into problems - for life I can’t figure out how to get my play / pause, which is called from the iOS control center . Here is the code that I use in my main view controller:

override func viewDidLoad() { super.viewDidLoad() self.musicPlayer = MPMusicPlayerController.applicationMusicPlayer() self.registerForMediaPlayerNotifications() UIApplication.sharedApplication().beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.sharedCommandCenter() commandCenter.previousTrackCommand.enabled = false commandCenter.previousTrackCommand.addTarget(self, action: "previousTrack") commandCenter.nextTrackCommand.enabled = false commandCenter.nextTrackCommand.addTarget(self, action: "nextTrack") commandCenter.togglePlayPauseCommand.enabled = true commandCenter.togglePlayPauseCommand.addTarget(self, action: "playOrPauseMusic") commandCenter.pauseCommand.addTarget(self, action: "playOrPauseMusic") commandCenter.pauseCommand.enabled = true commandCenter.playCommand.addTarget(self, action: "playOrPauseMusic") commandCenter.playCommand.enabled = true [...] } func previousTrack() { } func nextTrack() { } func playOrPauseMusic() { print("playOrPause") } 
+5
source share
3 answers

I had the same problem and I noticed that the callback for togglePlayPauseCommand not called, but the previousTrackCommand was. So after some experimentation, I got this working by removing togglePlayPauseCommand and instead individually executing the built-in callbacks for playCommand and pauseCommand - note that using custom selectors does not work, they should be built-in callbacks.

 let commandCenter = MPRemoteCommandCenter.shared() commandCenter.playCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in moviePlayer.prepareToPlay() moviePlayer.play() return MPRemoteCommandHandlerStatus.success } commandCenter.pauseCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in moviePlayer.pause() return MPRemoteCommandHandlerStatus.success } 
+3
source

Try adding Required background modes to Info.plist as follows:

Info.plist screenshot

+1
source

put your code in viewDidApper.

-3
source

Source: https://habr.com/ru/post/1241133/


All Articles