Ios 无法分配类型为';UIImage?&x27;输入';NSData?&x27;斯威夫特3

Ios 无法分配类型为';UIImage?&x27;输入';NSData?&x27;斯威夫特3,ios,swift,uiimage,Ios,Swift,Uiimage,我正在为应用程序使用CoreData。我在数据模型中将图像设置为BinaryData。但我已经从服务器中获取了图像作为UIImage,它抛出的错误如下: cannot assign value of type 'UIImage?' to type 'NSData? 我搜索了一下,但找不到任何相似的解决方案。有人能在swift 3中帮助我吗? 我的代码是: let url1:URL = URL(string:self.appDictionary.value(forKey: "image") as

我正在为应用程序使用
CoreData
。我在数据模型中将图像设置为
BinaryData
。但我已经从服务器中获取了图像作为
UIImage
,它抛出的错误如下:

cannot assign value of type 'UIImage?' to type 'NSData?
我搜索了一下,但找不到任何相似的解决方案。有人能在swift 3中帮助我吗?
我的代码是:

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?'
   }
})

错误信息非常清楚-无法将
UIImage
对象分配给
NSData
类型的变量

要将
UIImage
转换为Swift的
数据
类型,请使用
UIImagePNGRepresentation

var data : Data = UIImagePNGRepresentation(image)

请注意,如果您使用的是Swift,您应该使用Swift的类型
Data
,而不是
NSData

,您必须将图像转换为
数据(或
NSData
),以支持
imagenews
数据类型

试试这个

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)
        }
    }

变量task.imagenews的类型是什么?为了帮助您,我们需要更多。什么是task.imagenews?你想用它做什么?你的答案很好。。我把它弄得很复杂