JSON Feed未在Tableview中显示

时间:2017-12-06 20:45:43

标签: json swift api uitableview

我在桌面视图中显示数据时遇到问题。我知道我到达了数据,因为我已经设置了打印功能,显示数据是另一回事。作为参考,这是一个来自和API的JSON源,在https://api.opendota.com/api/rankings列出。如果有人有任何建议,我将不胜感激。谢谢。

import UIKit

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

//Optional objects are defined using ?
struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var rankTable: UITableView!

    var rank = [PlayerStats]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //this is an optional URL, so need to define objects in contains
        let jsonUrlString = "https://api.opendota.com/api/rankings"
        guard let url = URL(string: jsonUrlString) else {return}
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else {return}
            //let dataAsString = String(data: data, encoding: .utf8)
            //print(dataAsString)

            do{
                let downloadedRank = try JSONDecoder().decode(PlayerStatsParent.self, from: data)
                self.rank = downloadedRank.rankings
                DispatchQueue.main.async {
                    self.rankTable.reloadData()
                }
                print(downloadedRank.rankings)
            } catch let jsonErr {
                print("Error jsonErr", jsonErr)
            }
        }.resume()
    }

    let jsonUrlString = "https://api.opendota.com/api/rankings"

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
        cell.nameLabel.text = rank[indexPath.row].personaname

        return cell
    }

1 个答案:

答案 0 :(得分:1)

除非您在故事板中设置了UITableView委托和dataSource,否则需要在viewDidLoad中执行此操作,如下所示:

self.rankTable.delegate = self
self.rankTable.dataSource = self

否则你的tableview无法获取数据。