Jerland2 Jerland2 - 20 days ago 10
Swift Question

iOS Swift - MPCommandCenter & NowPlayingInfoCenter Controlling Music on Lock Screen

I am creating a music player (In Swift 3) that uses MPMediaItems and MPMediaPlayerController. I cannot for the life of me figure out how to control music from the lock screen or notification center...

I have read every article I can find on MPRemoteCommandCenter and MPNowPlayingInfoCenter and I cannot get it to work.

I have enabled background music playback, currently the music continues playing outside of the app, but does not received remote commands.

Below is the code currently being used

In my View Did Load I call the following function

let player = MPMusicPlayerController.applicationMusicPlayer()
let commandCenter = MPRemoteCommandCenter.shared()

func configureCommandCenter() {
print("Enter configuration")
self.commandCenter.playCommand.addTarget { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
print("Play")
sself.player.play()
self?.getNowPlayingItem()
return .success
}

self.commandCenter.pauseCommand.addTarget { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
print("Pause")
sself.player.pause()
self?.getNowPlayingItem()
return .success
}

self.commandCenter.nextTrackCommand.addTarget { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
print("next")
sself.player.skipToNextItem()
self?.getNowPlayingItem()
return .success
}

self.commandCenter.previousTrackCommand.addTarget { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
print("Prev")
sself.player.skipToPreviousItem()
self?.getNowPlayingItem()
return .success
}

}


To reiterate my project compiles fine, plays media, continues playing media when app is not in focus and when phone is locked, however no commands are seen from within the app, resulting in the app not being able to be controlled from the lock screen or notification center. Any help would be greatly appreciated.

I would also like to mention that I have looked at the Apple API Docs related to both RemoteCommands and InfoCenter.

Am I missing some key step in order to get remote commands registering from within the app?

Answer

The problem is that your player is MPMusicPlayerController.applicationMusicPlayer(). You cannot use the application music player as a remote control target.

If you want remote control target capabilities, you need your player to be something like an AVAudioPlayer.

Comments