简体   繁体   中英

cannot assign value of type 'UIImage?' to type 'NSData?' in swift 3

I am using CoreData for an app. I have set image as BinaryData in data model. But I have fetched image from server as UIImage and it throws error as:

cannot assign value of type 'UIImage?' to type 'NSData?

I searched but couldn't find any resemblance solution for it. Can anyone help me in swift 3?
My code is:

let url1:URL = URL(string:self.appDictionary.value(forKey: "image") as! String)!
let picture = "http://54.243.11.100/storage/images/news/f/"
let strInterval = String(format:"%@%@",picture as CVarArg,url1 as CVarArg) as String as String
let url = URL(string: strInterval as String)
SDWebImageManager.shared().downloadImage(with: url, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
   if self != nil {
      task.imagenews = image //Error:cannot assign value of type 'UIImage?' to type 'NSData?'
   }
})

The error message is pretty clear - you cannot assign UIImage object to a variable of NSData type.

To convert UIImage to Swift's Data type, use UIImagePNGRepresentation

var data : Data = UIImagePNGRepresentation(image)

Note that if you're using Swift, you should be using Swift's type Data instead of NSData

You must convert, image into Data (or NSData ) to support imagenews data type.

Try this

let url1:URL = URL(string:self.appDictionary.value(forKey: "image") as! String)!
let picture = "http://54.243.11.100/storage/images/news/f/"
let strInterval = String(format:"%@%@",picture as CVarArg,url1 as CVarArg) as String as String
let url = URL(string: strInterval as String)
SDWebImageManager.shared().downloadImage(with: url, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
   if self != nil {

     if let data = img.pngRepresentationData {  // If image type is PNG
           task.imagenews = data     
      } else if let data = img.jpegRepresentationData { // If image type is JPG/JPEG
          task.imagenews = data     
     } 


   }
})



// UIImage extension, helps to convert Image into data
extension UIImage {

        var pngRepresentationData: Data? {
            return UIImagePNGRepresentation(img)
        }

        var jpegRepresentationData: Data? {
            return UIImageJPEGRepresentation(self, 1.0)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM