如何使用Swift4中的Codable协议用JSON数据填充TableViewCell?

时间:2017-08-17 20:09:23

标签: tableview swift4

解决

我正在尝试从此链接https://api.myjson.com/bins/13axs1中的示例 JSON 填充表视图单元格,但在尝试分配textLabel时在cellForRowAt函数中收到错误。

  

键入' [城市]?'没有下标成员

JSON

[
  {
    "name": "New York",
    "information": "Later will be added",
    "imageUrl": "later"
  },
  {
    "name": "New York",
    "information": "Later will be added",
    "imageUrl": "later"
  }
]

ViewController中的代码:

struct City: Codable {
    let name: String?
    let information: String?
    let imageUrl: String?
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var citiesList: [City] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrlString = "https://api.myjson.com/bins/13axs1"
        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, err) in

            guard let data = data else { return }

            do {
                let cities = try JSONDecoder().decode([City].self, from: data)

                if cities != nil{
                   self.citiesList = cities
               }else {
                   print("nothing to display")
               }

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

            } catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }

        }.resume()

    }

}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return citiesList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = citiesList[indexPath.row].name // here I am getting error type '[City]? has no subscript members
        return cell
    }
}

很抱歉,但我不知道为什么在我添加之后所有代码都没有清楚地显示出来,但希望很明显让大家明白,非常感谢。

1 个答案:

答案 0 :(得分:0)

您缺少重装方法(reloadData()):

URLSession.shared.dataTask(with: url) { (data, response, err) in

    guard let data = data else { return }

    do {
        let cities = try JSONDecoder().decode([City].self, from: data)
        self.citiesList = cities

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    } catch {
        print("Error serializing json:", error)
    }

}.resume()


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.deque...
    cell.textLabel?.text = citiesList?[indexPath.row].name
    return cell
}