Swift 3 上的 JSON 图像

标签 json swift image

我需要将字符串转换为图像,但出现此错误:

“错误无法将字符串类型的值转换为预期的参数类型“数据””

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

最佳答案

您应该将 json 序列化为 ["string":Any] 并稍后将值转换为 String 和 Data。如果您确定“fondo”在您的后端属于数据类型,那么这应该可以工作

像这样:

 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 类型。

关于Swift 3 上的 JSON 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005568/

相关文章:

swift - 为什么 'if let' 似乎不像以前在 Xcode 8.3 beta 中的 Swift 3 中拆箱值?

swift - 在联系人中存储自定义标签和日期

php - 使用 PHP 将特定的 RGB 颜色替换为另一个图像

javascript - 初始化在 jQuery $.getJSON 回调函数外部声明的变量

ios - 在 SpriteKit 中随着时间的推移减小 CGPath 的大小?

将图像编码和解码为 Base64 时出现 java 内存不足异常

html - 水平对齐,文本在图像顶部?

jquery - Grails 多个 JQgrid

mysql - 在 MySQL 中将 JSON 数据存储为文本

javascript - 通过对象解构和三元运算符组合对象