如何将JSON Image-String(而不是url)转换为UIImage以供查看

时间:2017-11-21 18:03:00

标签: ios json swift xcode

嘿所以我现在已经尝试解决这个问题了一天。所以我迫切希望得到答案。我想要做的事实上很简单,我有一个字符串形式的JSON数组(我认为)。它们不是url的图像/字符串是JSON,就像这个“GoodLogo.png”一样,问题是来自JSON的常见图像是url格式。但这只是说png& JPG

JSON代码我回来了:

(
    {
    id = 1;
    logo = "scriptslogo.png";
    name = "scripts";
},
    {
    id = 2;
    logo = "altrlogo.jpg";
    name = "Altr";
},
    {
    id = 3;
    logo = "bostonlogo.jpeg";
    name = "boston";
},
)

我有一个变量,它是一个字符串数组。我将JSON数据放入。

代码:

    var imageList = [String]()

    let string = "https://some.url/api"

    let url = NSURL(string: string)

    let request = NSMutableURLRequest(url: url! as URL)

    request.httpMethod = "GET"

    let session = URLSession.shared

    let tache = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray {

            let logo = jsonObj.value(forKey: "logo") as? NSArray
            self.imageList = logo as! [String]


            DispatchQueue.main.async {
            self.imageTableView.reloadData()
            }
        }

    }
    tache.resume()

然后我所做的就是尝试填充tableview,但我尝试过的每一种方式都会崩溃应用程序或者没有显示任何内容。

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == imageTableView {

            cell = imageTableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! imageCell

            cell.cellImage.image = imageList[indexPath.row]


          // Iv'e tried this which I don't no if it even applies to what I'm trying to do 

          if let imageData = Data(base64Encoded: imageList[indexPath.row], options: .ignoreUnknownCharacters) {
          let image = UIImage(data: imageData)
          cell.cellImage.image = image
        }


    }
    return cell

1 个答案:

答案 0 :(得分:0)

试一下

let url = URL(string: "http://test.com/images/\(imageList[indexPath.row])")
let data = try? Data(contentsOf: url)

if let imageData = data {
    cell.cellImage.image = UIImage(data: data)
}