How to update MPNowPlayingInfoCenter in Swift?
Asked Answered
P

3

6

In objective c, I've been using code like this to update MPNowPlayingInfoCenter:

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

But in Swift, it doesn't seem like the function "setNowPlayingInfo" is recognized:

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

Is there anything I'm missing?

Politesse answered 17/6, 2014 at 18:34 Comment(2)
try MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!", MPMediaItemPropertyTitle : "Title!], setters/getters behave quite differently in Swift from ObjCStopgap
@JackWu thanks so much. Yep, still getting the hang of Swift.Politesse
S
5

In Swift, getters/setters work differently. Since there are no more properties like in ObjC, there are no automatically generated setters/getters for you. You should just access the variable directly.

In your case, use:

MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!",  MPMediaItemPropertyTitle : "Title!"]
Stopgap answered 17/6, 2014 at 18:58 Comment(1)
As of today, i can't get it to work... get a error type "String" does not conform to protocol 'AnyObject'Iva
M
1

Swift 2, this also work:

let songInfo: [String:AnyObject] = [
         MPMediaItemPropertyTitle: mySoundTrack.TrackName,
         MPMediaItemPropertyArtist: String(mySoundTrack.TrackID),
         MPMediaItemPropertyArtwork: albumArt
]

MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo
Montherlant answered 10/10, 2015 at 0:37 Comment(0)
H
0

Previous answer by @Jack no longer works as is, and needs some modifications.

Swift 3 compiler complains about 2 things.

  • String is not directly convertible to AnyObject, and so the two dictionary entry values must be casted from String to AnyObject.
  • defaultCenter() has been renamed to default().

so a viable code will look like this:

MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!" as AnyObject,  MPMediaItemPropertyTitle : "Title!" as AnyObject]
Headquarters answered 4/7, 2017 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.