Search code examples
iosswift2mpnowplayinginfocenter

MPNowPlayingInfoCenter nowPlayingInfo error in Swift 2


This works with Swift 1, but reports error in Swift 2:

let image:UIImage = UIImage(named: getStringForLanguage(french: "lock_en", english: "lock_fr.") as! String)!
let albumArt = MPMediaItemArtwork(image: image)
let songInfo: NSMutableDictionary = [
    MPMediaItemPropertyTitle: "",
    MPMediaItemPropertyArtist: "",
    MPMediaItemPropertyArtwork: albumArt
]


MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo // this reports the error

Error message:

Cannot assign a value of type 'NSMutableDictionary' to a value of type '[String : AnyObject]?'


Solution

  • You followed my comment quite literally. :)

    What I meant is that the type for .nowPlayingInfo is now a Swift dictionary, [String : AnyObject]?, instead of a NSMutableDictionary from Foundation.

    And since Swift 2's compiler correctly infers the type of the dictionary, there's no need to declare the type.

    Just write:

    let songInfo = [
        MPMediaItemPropertyTitle: "",
        MPMediaItemPropertyArtist: "",
        MPMediaItemPropertyArtwork: albumArt
    ]
    

    If you need to be explicit, the right type is not Dictionary (although it works) but [String : AnyObject]?:

    let songInfo: [String: AnyObject]? = [
        MPMediaItemPropertyTitle: "",
        MPMediaItemPropertyArtist: "",
        MPMediaItemPropertyArtwork: albumArt
    ]
    

    The type is an Optional because the .nowPlayingInfo property can be set to nil.