I am converting a project from Xcode 7 iOS 9 Swift 2 to Xcode 8 iOS 10 Swift 3. I let Xcode convert to the latest and it produced:
let artWork = delegate.musicPlayer.nowPlayingItem?.value(forProperty: MPMediaItemPropertyArtwork)
let imageForButton = (artWork as AnyObject).image(at: CGSize(width: 300, height: 300))
This resulting code crashes the app and pops the error:
-[_SwiftValue imageWithSize:]: unrecognized selector sent to instance 0x17008cdf0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue imageWithSize:]: unrecognized selector sent to instance
For completeness, the original line in Xcode 7 Swift 2 was:
let imageForButton = artWork?.imageWithSize(CGSizeMake(300, 300))
What is the correct way to size an image in Swift 3?
valueForProperty
returns Any?
, you need to cast the value to the actual type
if let artWork = delegate.musicPlayer.nowPlayingItem?.value(forProperty: MPMediaItemPropertyArtwork) as? MPMediaItemArtwork {
let imageForButton = artWork.image(at: CGSize(width: 300, height: 300))
}