How to update MPNowPlayingInfoCenter in Swift?

In object c, I used this code to update MPNowPlayingInfoCenter:

[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo: @{ MPMediaItemPropertyArtist : @"Artist!", MPMediaItemPropertyTitle : @"Title! }]; 

But in Swift, this is not like the "setNowPlayingInfo" function:

 MPNowPlayingInfoCenter.defaultCenter().... // Can't identify 'setNowPlayingInfo()' 

Is there anything I don't see?

+6
source share
4 answers

In Swift, getters / seters work differently. Since ObjC no longer has properties, there are no automatically created setters / getters for you. You should just access the variable directly.

In your case, use:

 MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!", MPMediaItemPropertyTitle : "Title!"] 
+5
source

Swift 2, this also works:

 let songInfo: [String:AnyObject] = [ MPMediaItemPropertyTitle: mySoundTrack.TrackName, MPMediaItemPropertyArtist: String(mySoundTrack.TrackID), MPMediaItemPropertyArtwork: albumArt ] MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo 
+1
source

The previous answer from @Jack no longer works as is and needs some modifications.

The Swift 3 compiler complains about 2 things.

  • A string is not directly converted to AnyObject, and therefore two dictionary entries must be written from String to AnyObject.
  • defaultCenter() been renamed to default() .

therefore, viable code would look like this:

 MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!" as AnyObject, MPMediaItemPropertyTitle : "Title!" as AnyObject] 
0
source

Did you wrap it like a string?

 var artist = dictionary["artist"]! as String var title = dictionary["title"]! as String MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyArtist : artist, MPMediaItemPropertyTitle : title] 
-2
source

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


All Articles