Данные из API не отображаются в моем UITableView - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь отобразить данные из API в UITableView. У меня проблема в том, что я не получаю никаких данных, поступающих в UITableView. Теперь я вижу, что в моем источнике данных и делегате связаны. Data Source and Delegate Я также знаю, что у меня есть доступ к API, поскольку я могу печатать на консоли.

Нет ошибок только из-за того, что я не вижу никаких данных. Ниже приведен код, который у меня есть.

class StandingTableViewController: UITableViewController {

var standing = ""
let SEASON_URL = "https://ergast.com/api/f1"

var champions: [DriverStanding] = []
override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.title = standing

    fetchJSON(standing: standing)

}
private func fetchJSON(standing: String){
    let JsonUrlString = SEASON_URL + "/" + String(standing) + "/driverstandings.json"
    print(JsonUrlString)
    guard let url = URL(string: JsonUrlString) else { return }

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

        DispatchQueue.main.async {
            if let err = err {
                print("Failed to get data from url:", err)
                return
            }

            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                // Swift 4.1
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let firstDriver = try decoder.decode(F1Data.self, from: data)
                self.champions = firstDriver.mrData.standingsTable.standingsLists[0].driverStandings
                self.tableView.reloadData()

            } catch {
                print(error)
            }
        }
    }.resume()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 0
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return champions.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")

    let champion = champions[indexPath.row]
    let driverName = "\(champion.driver.givenName!) \(champion.driver.familyName!)"
    cell.textLabel?.text = driverName


    return cell
}

Любая помощь будет оценена. Я проверил, что "cellId" совпадает с тем, что есть в моем коде.

Ответы [ 2 ]

1 голос
/ 26 марта 2019

В numberOfSections вернуть 1 или удалить весь метод в качестве значения по умолчанию равно 1

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 0
}

И повторно использовать ячейки, установить стиль субтитров в Интерфейсном Разработчике и написать

let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
0 голосов
/ 26 марта 2019

Есть какие-нибудь обновления по этому поводу?Работал ли метод удаления:

override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}

работает?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...