2016-12-06 20 views
0

我需要轉換的字符串的圖像,我得到這個錯誤:JSON圖像3

「?錯誤不能轉換String類型的值與預期的參數類型‘數據’」

let url = URL(string: "http://******************")! 
    let request = URLRequest(url: url) 

    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     guard let data = data else { 
      print("solicitud fallida \(error)") 
      return 
     } 

     do { 

      print("recibimos respuesta") 

      if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] { 

       DispatchQueue.main.async { 
        let nombre = json["nombre"] 
        self.urllabel.text = nombre 

        let backimg = json["fondo"] 
        self.imgfondo.image = UIImage(data: backimg) 
       } 
+1

'json [「fondo」]'包含一個字符串。你爲什麼試圖將它傳遞給期望Data的方法? – rmaddy

回答

0

你應該讓你將json序列化爲[「string」:Any],並稍後將值轉換爲String和Data。如果你確定「豐多」是類型數據的後端,那麼這應該工作

像這樣:

if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any?] { 

      DispatchQueue.main.async { 
       if let nombre = json["nombre"] as? String{ 
        self.urllabel.text = nombre 
       } 


       if let backimg = json["condo"] as? Data{ //Is this of type Data in you backend? //Data is the same as NSData prior to Swift 3 
        self.imgfondo.image = UIImage(data: backimg) 
       } 

      } 

的原因,你的解決方案沒有奏效,是因爲你試圖讓圖像從一個字符串,當你應該已經傳入一種類型的NSData。

+1

它是Swift 3,不要使用'NSData',使用'Data'。 – rmaddy

+0

從錯誤中可以明顯看出,'json [「fondo」]'包含'String',而不是'Data'。 – rmaddy

+0

錯誤字符串出現是因爲他將我們的答案中指出的他的JSON序列化爲[string:string]而不是[「string」:Any]!目前尚不清楚他從他的支持中獲得的數據是什麼,但如果數據類型爲Data,我的回答是正確的。 – Starlord

0

它看起來像你能夠成功地通過解包你的JSON響應爲[String: String],這意味着你必須將你的圖像字符串轉換爲數據對象。這不是數據。只是爲了確保 - 你得到的字符串是一個數據字符串,而不是一個圖像的url字符串?

我回答下面假設它是一個數據字符串。

if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] { 

    DispatchQueue.main.async { 
     if let nombre = json["nombre"] as? String { 
     self.urllabel.text = nombre 
     } 

     if let backImgString = json["condo"] as? String { 
     if let backImgData = backImgString.dataUsingEncoding(NSUTF8StringEncoding) as? NSData { 
      self.imgfondo.image = UIImage(data: backImgData) 
     } else { 
     //handle error here 
     } 
     } else { 
     //handle error here 
     } 
    } 
}