json - 如何将 JSON 数据下载到 TableView 中?

标签 json swift uitableview

我想显示数据但是运行时我无法显示任何东西

 import UIKit

class AnimalTableViewController: UITableViewController {
final let urlString = "https://doc-00-4k-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/ncme2210ej4sg6n7p7ipm3bmm6mht9s8/1568275200000/00096549938281215637/*/1aE90llwaDYEGS9Ci3nSmBUfaD75Rf6PD?e=download"


var nameArray = [String]()
var catArray = [String]()
var imgURLArray = [String]()


override func viewWillAppear(_ animated: Bool) {
    downloadJsonWithURL()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nameArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AnimalsCell") as! TableViewCell
    cell.nameLabel.text = nameArray[indexPath.row]
    cell.catLabel.text = catArray[indexPath.row]

    let imgURL = NSURL(string: imgURLArray[indexPath.row])

    if imgURL != nil {
        let data = NSData(contentsOf: (imgURL as URL?)!)
        cell.imgView.image = UIImage(data: data! as Data)

    }

    return cell
}

func downloadJsonWithURL() {
    let url = NSURL(string: urlString)
    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            print(jsonObj.value(forKey: "animals")!)

            if let actorArray = jsonObj.value(forKey: "animals") as? NSArray {
                for actor in actorArray{
                    if let actorDict = actor as? NSDictionary {
                        if let name = actorDict.value(forKey: "name") {
                            self.nameArray.append(name as! String)
                        }
                        if let name = actorDict.value(forKey: "category") {
                            self.catArray.append(name as! String)
                        }
                        if let name = actorDict.value(forKey: "image") {
                            self.imgURLArray.append(name as! String)
                        }

                    }
                }
            }

            OperationQueue.main.addOperation({
                self.tableView.reloadData()
            })
        }
    }).resume()
}

最佳答案

使用 Dispatchqueue 而不是 OperationQueue

DispatchQueue.main.async {

并创建一个包含结构的数组,而不是使用 3 个单独的数组

struct Animal {
    let name: String
    let category: String
    let image: String
}

并且不要使用 NS 类

//...
if let animals = jsonObj.value(forKey: "animals") as? [Any] {
    for actor in animals {
        if let actorDict = actor as? [String: Any] {
            animal = Animal()
            if let name = actorDict["name"] as? String {
                animal.name = name
            }
            if let category = actorDict["category"] as? String {
                animal.category = category               
            }
            if let imageUrl = actorDict["image"] as? String {
                animal.imageUrl = imageUrl
            }
            self.animalArray.append(animal)
        }
    }
}

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

self.animalArray 在哪里

var animalArray: [Animal]

关于json - 如何将 JSON 数据下载到 TableView 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57918346/

相关文章:

json - jackson self 引用导致循环

ios - 每次调试测试后文档位置发生变化

ios - 在 Objective C 的 FooterTableViewCell 中放置 View 的问题

json - Elixir/Phoenix 将 JSON 保存到 Postgres 数据库

javascript - google电子表格导出为json文件,如何格式化?

ios - 在 ios swift 中使用 alamofire 请求超时错误 1001?

Swift 2.2 单例

ios - 尝试在 iOS 中使用单例模式重构网络方法

iOS 应用向右移动,无法查看完整表格

ios - NSJSONSerialization 拆箱 NSNumber?