Как я могу поместить данные Json в UITableView, используя Swift 4? - PullRequest
0 голосов
/ 07 февраля 2019

У меня это здесь структурировано:

struct Excercise: Codable {
    let excerciseID: String
    let excerciseName: String
    let description: String
    let intensity: Int
}

Тогда это переменная:

var excercistList = [Excercise]()

И cellforrowat:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ExcerciseCell", for: indexPath)
    cell.textLabel?.text = self.excercistList[indexPath.row].excerciseName
    return cell
}

Это URLSession:

 URLSession.shared.dataTask(with: url) { (data, response, err) in
                        guard let data = data else{return}

   do {
         let excerciseList = try JSONDecoder().decode(Excercise.self, from: data)
         print(excerciseList.excerciseName)
      } catch let jsonErr {
           print("Error", jsonErr)
      }
  }.resume()

Я получил правильные результаты на распечатке, но ничего на столе.

Что я делаю не так?

1 Ответ

0 голосов
/ 07 февраля 2019

Прежде всего, вы должны заполнить свой dataSource, который равен var excercistList = [Excercise]().После этого вам нужно перезагрузить tableView.

URLSession.shared.dataTask(with: url) { (data, response, err) in
                        guard let data = data else{return}

   do {
         let excerciseListFromDecoder = try JSONDecoder().decode(Excercise.self, from: data)
        self.excercistList =  excerciseListFromDecoder
        self.tableView.reloadData()
      } catch let jsonErr {
           print("Error", jsonErr)
      }
  }.resume()

. Вы должны быть уверены, что правильно установили

tableView.delegate = self
tableView.dataSource = self

и numberOfRowsInSection

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.excercistList.count
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...