【问题标题】:TableView not populating data, but JSON file is being processedTableView 未填充数据,但正在处理 JSON 文件
【发布时间】:2018-05-23 07:06:03
【问题描述】:

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

这是我的 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 {$0.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 已读取,然后我看到“在部分中找到 0 行”打印再次。

我在这里错过了什么?

【问题讨论】:

    标签: json swift4 xcode9


    【解决方案1】:

    在您从bonuses 数组中读取的数据源方法中。但是,当您下载完帖子后,您并没有将帖子的奖金分配给您的 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 {$0.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()
    }
    

    【讨论】:

    • 对于以后可能会发现此问题的任何其他人,@nayem 的答案中提到的//做任何可以转换为奖金的事情都设置为self?.bonuses = posts.bonuses,这解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多