UIImage to NSData for Core Data in Swift 3.0

Jason Brady picture Jason Brady · Oct 3, 2016 · Viewed 28.4k times · Source

So previously, in Swift 2.2 I could use Entity.image = UIImagePNGRepresentation(UIImage(named: "Image Name")!)

But now in Swift 3.0 it appears that we now have to use an extra step. Entity.image = NSData(data: UIImagePNGRepresentation(UIImage(named: "Image Name")!)) Or the object equivalent of UIImage(name: "Image Name")

Is there a new way in Swift 3.0 to go from UIImage to NSData?

Answer

Quang Hà picture Quang Hà · Oct 3, 2016

Try this:

if let img = UIImage(named: "hallo.png") {
    let data = UIImagePNGRepresentation(img) as NSData?
}