Search code examples
iosswiftmpnowplayinginfocenter

How to update MPNowPlayingInfoCenter when using MPMusicPlayerApplicationController


I'm trying to update MPNowPlayingInfoCenter with the song info of a track that I'm playing from Apple Music. I have done the following:

Set my background mode to: "Audio, Airplay, and Picture in Picture",

Correctly set my AVAudioSession category:

let session = AVAudioSession.sharedInstance()

do {
    try session.setCategory(AVAudioSessionCategoryPlayback, with: [])
    try session.setActive(true)
} catch let error as NSError {
    print("Failed to set the audio session category and mode: \(error.localizedDescription)")
}

Setup the MPRemoteCommandCenter to respond to remote commands:

let commandCenter = MPRemoteCommandCenter.shared();
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget {event in
    self.player.play()
    return .success
}
commandCenter.pauseCommand.isEnabled = true
commandCenter.pauseCommand.addTarget {event in
    self.player.pause()
    return .success
}
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget {event in
    self.goForward()
    return .success
}
commandCenter.previousTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.addTarget {event in
    self.goBack()
    return .success
}

And updating MPNowPlayingInfoCenter with correct information on-start and whenever there are playback events:

let info: [String:Any] = [
    MPMediaItemPropertyAlbumTitle : albumTitle,
    MPNowPlayingInfoCollectionIdentifier : albumId,
    MPMediaItemPropertyArtist : artistName,
    MPNowPlayingInfoPropertyMediaType : mediaType,
    MPMediaItemPropertyPersistentID : trackId,
    MPMediaItemPropertyTitle : trackTitle,
    MPMediaItemPropertyPlaybackDuration : trackDuration,
    MPNowPlayingInfoPropertyExternalContentIdentifier : trackId,
    MPNowPlayingInfoPropertyPlaybackRate : isPlaying ? 1.0 : 0.0,
    MPNowPlayingInfoPropertyPlaybackProgress : 0.5,
    MPMediaItemPropertyArtwork : MPMediaItemArtwork(boundsSize: CGSize(width: 100, height: 100), requestHandler: { (size: CGSize) -> UIImage in
        return UIImage(named: "play")! // dummy purposes
    })
]

let infoCenter = MPNowPlayingInfoCenter.default()
infoCenter.nowPlayingInfo = info
infoCenter.playbackState = isPlaying ? .playing : .paused

What more do I need to do in order for the song info to appear in Control Center and on the lock screen?


Solution

  • Turns out that the code is 100% correct, but was a bug in iOS 11, previous to 11.3. With the official release of 11.3 this week, the code above now works as Apple intended with MPMusicPlayerApplicationController.