2017-09-07 77 views
0

我使用CoreData爲應用程序。我在數據模型中將圖像設置爲BinaryData。但是,我要取的圖像從服務器UIImage和它拋出錯誤爲:無法指定'UIImage?'類型的值鍵入'NSData?'在迅速3

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

我搜查,但找不到任何相似的解決方案。任何人都可以幫助我迅速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?' 
    } 
}) 
+0

什麼是變量task.imagenews的類型? –

+0

爲了幫助我們,我們需要更多。什麼是task.imagenews?你想用它做什麼? –

回答

2

的錯誤信息是非常明確的 - 你不能UIImage對象賦給NSData類型的變量。

要轉換UIImage斯威夫特的Data類型,使用UIImagePNGRepresentation

var data : Data = UIImagePNGRepresentation(image) 

請注意,如果你使用的斯威夫特,你應該用斯威夫特的類型Data而不是NSData

+0

你的答案不錯。我讓它變得非常複雜 – Krunal

0

您必須轉換,圖像成Data(或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) 
     } 
    } 
相關問題