TableView 未填充数据,但正在处理 JSON 文件

TableView not populating data, but JSON file is being processed

我在从托管的 JSON 文件中填充 table 视图时遇到问题。我已经确认该应用程序已成功查看 JSON 文件中的数据,但 table 本身仍然是空白的(奇怪的是,某些行显示了两个不同的垂直高度)。

这是我的 ViewController.swift:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    // var heroes = [HeroStats]()
    var bonuses = [JsonFile.JsonBonuses]()

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadJSON {
            self.tableView.reloadData()
        }

        tableView.delegate = self
        tableView.dataSource = self
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("Found \(bonuses.count) rows in section.")
        return bonuses.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = bonuses[indexPath.row].name.capitalized
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "showDetails", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? HeroViewController {
            destination.bonus = bonuses[(tableView.indexPathForSelectedRow?.row)!]
        }
    }

    // MARK: - Download JSON from ToH webserver
    func downloadJSON(completed: @escaping () -> ()) {
        let url = URL(string: "http://tourofhonor.com/BonusData.json")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error == nil {
                do {
                    let posts = try JSONDecoder().decode(JsonFile.self, from: data!)
                    DispatchQueue.main.async {
                        completed()
                    }
                    print(posts.bonuses.map {[=11=].bonusCode})
                } catch {
                    print("JSON Download Failed")
                }
            }
        }.resume()
    }
}

下面是 JsonFile.swift 文件的样子:

import Foundation

struct JsonFile: Codable {
    struct Meta: Codable {
        let fileName: String
        let version: String
    }
    struct JsonBonuses: Codable {
        let bonusCode: String
        let category: String
        let name: String
        let value: Int
        let city: String
        let state: String
        let flavor: String
        let imageName: String
    }
    let meta: Meta
    let bonuses: [JsonBonuses]
}

tableView numberOfSections 中的打印显示 0,我注意到我看到它打印了 3 次,然后我看到代码打印表明 JSON 已被读取,然后我再次看到 "Found 0 rows in section" 打印。

我在这里错过了什么?

在数据源方法中,您正在读取 bonuses 数组。但是,当您下载完 post 后,您并没有将 post 的奖励分配给 bonuses 数组。

func downloadJSON(completed: @escaping () -> ()) {
    let url = URL(string: "http://tourofhonor.com/BonusData.json")
    URLSession.shared.dataTask(with: url!) { [weak self] (data, response, error) in
        if error == nil {
            do {
                let posts = try JSONDecoder().decode(JsonFile.self, from: data!)
                DispatchQueue.main.async {
                    completed()
                }
                print(posts.bonuses.map {[=10=].bonusCode})
                // Here you need to assign the bonuses from your posts to your bonuses array
                // Pay attention to the [weak self] that is added in the function call
                self?.bonuses = ... // do anything that converts to bonuses
            } catch {
                print("JSON Download Failed")
            }
        }
    }.resume()
}