Table 查看未填充数据,但我的打印语句有效

Table View not populating data, but my print statements are working

当我 运行 下面的代码时,我在我的控制台日志中得到了正确的 JSON 版本和奖励代码列表,但是 table 视图本身没有显示任何数据.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

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!) { [weak self] (data, response, error) in
        if error == nil {
            do {
                let posts = try JSONDecoder().decode(JsonFile.self, from: data!)
                DispatchQueue.main.async {
                    completed()
                }
                print("JSON Version \(posts.meta.version) loaded.")
                print(posts.bonuses.map {[=11=].bonusCode})
                self?.bonuses = posts.bonuses
            } catch {
                print("JSON Download Failed")
            }
        }
    }.resume()
}
}

该代码基于我在网上找到的教程,该教程最初使用 DOTA 字符信息来填充数据。我将其更改为使用我自己的 JSON 提要,这似乎是有效的,因为我可以在控制台中看到奖励代码,但没有在应用程序中显示任何数据。

问题是您在填充 self.bonuses 数组之前调用了完成闭包,请尝试将其放在该行之后。

我还建议添加这些行:

tableView.delegate = self
tableView.dataSource = self

在调用 downloadJSON 方法之前。

API 正在异步工作,因此 table 在 API 调用完成之前加载。所以你必须在 API 获取结果后重新加载 table。

            print(posts.bonuses.map {[=10=].bonusCode})
            self?.bonuses = posts.bonuses

            DispatchQueue.main.async {
                //reload table in the main queue
                self.myTableView.reloadData()
            }
        }