How to update MPNowPlayingInfoCenter when using MPMusicPlayerApplicationController

时间:2018-03-25 20:19:45

标签: ios swift mpnowplayinginfocenter

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?

1 个答案:

答案 0 :(得分:2)

事实证明代码是100%正确的,但是在11之前的iOS 11中是一个错误。随着本周11.3的官方发布,上面的代码现在可以像Apple一样使用MPMusicPlayerApplicationController

相关问题