I am building a music player app, and everything is working fine. I have been using the system music player so far, but now want to switch over to use an application music player instead, and that's where I'm running into problems - for the life of me I can't figure out how to get my play/pause callback to be called from the iOS control center. Here's the code I'm using 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")
}
I had this same issue and noticed that the callback for togglePlayPauseCommand
wasn't getting called, but previousTrackCommand
was. So after some experimentation I got this working by removing togglePlayPauseCommand
and instead indiviudally implementing the inline callbacks for playCommand
and pauseCommand
- please note that using custom selectors weren't working, they had to be the inline 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
}
Try adding Required background modes
to the Info.plist like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With