简体   繁体   English

在Swift 4中解析JSON后,为什么会得到空白的UITableView?

[英]Why am I getting a blank UITableView after parse JSON in Swift 4?

I can't figure out why the cells don't return with data. 我不知道为什么单元格不返回数据。

I can parse normally using the Decodable, which means that is working. 我可以使用Decodable正常解析,这意味着它可以正常工作。

I've been trying all the methods I find without success. 我一直在尝试所有发现的方法,但都没有成功。

struct MuscleGroup: Decodable {
   let ExcerciseID: String
   let description: String
   let excerciseName: String
   let muscleGroup: String
}


class ExerciseListViewController: UITableViewController {




var muscleGroup = [MuscleGroup]()


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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseList", for: indexPath) as! ExcerciseList

    let muscle = muscleGroup[indexPath.row]

    cell.textLabel!.text = muscle.excerciseName
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(self.muscleGroup[indexPath.row])
    tableView.deselectRow(at: indexPath, animated: true)
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.dataSource = self
    self.tableView.delegate = self
    getJson()

}




func getJson(){

    guard let url = URL(string: "https://jsonurl") else { return }

    let session = URLSession.shared
    session.dataTask(with: url) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            print(data)
            do {
                let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data)
                for muscle in muscles {


                    let muscleGroup = muscle.excerciseName
                    print(muscleGroup)
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }

                }
            } catch {
                print(error)
            }

        }
        }.resume()



}

If I change the var muscleGroup = String to ["Chest", "Back", "Abdominals","Arms", "Legs"] it returns correctly. 如果将var muscleGroup = String更改为[“ Chest”,“ Back”,“ Abdominals”,“ Arms”,“ Legs”],它将正确返回。

Also, the print result on the console returns all the data that needs to be on the Table View. 另外,控制台上的打印结果将返回需要在“表视图”中的所有数据。

What am I doing wrong? 我究竟做错了什么?

In your getJson function this line 在您的getJson函数中,此行

let muscleGroup = muscle.excerciseName

is creating a new local variable called muscleGroup , change the line to be 正在创建一个新的局部变量,名为muscleGroup ,将行更改为

self.muscleGroup.append(muscle.excerciseName)

ie get rid of the let and append the value to the main array variable 即摆脱let appendappend到主数组变量

Also move the 同时移动

 DispatchQueue.main.async {
     self.tableView.reloadData()
 }

to be outside of the for loop of muscles as you are forcing the table to reload for each entry rather than when you are finished 到外面的用于循环muscles ,你正迫使表重新加载每个条目,而不是当你完成

As you probably want to use the entire struct 因为您可能想使用整个结构

  1. Replace 更换

     var muscleGroup = [String]() 

    with

     var muscleGroups = [MuscleGroup]() 
  2. Replace 更换

     let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data) for muscle in muscles { let muscleGroup = muscle.excerciseName print(muscleGroup) DispatchQueue.main.async { self.tableView.reloadData() } } 

    with

     self.muscleGroups = try JSONDecoder().decode([MuscleGroup].self, from: data) DispatchQueue.main.async { self.tableView.reloadData() } 
  3. Replace 更换

     cell.textLabel?.text = self.muscleGroup[indexPath.row] 

    with

     cell.textLabel?.text = self.muscleGroups[indexPath.row].muscleGroup 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我第二次UITableView搜索后会收到NSInternalInconsistencyException? - Why am I getting an NSInternalInconsistencyException after my second UITableView search? 为什么在iOS加载屏幕后出现空白? - Why am I getting a blank slate after the iOS loading screen? 滚动后为什么UITableViewCell中出现双重内容? (迅速) - Why am I getting double content in UITableViewCell after scrolling? (Swift) 我正在尝试从 Swift subreddit 解析 JSON。 为什么我有问题? - I am trying to parse JSON from the Swift subreddit. Why am I having issues? 我正在尝试使用 Swift Codable 从 subreddit 解析 JSON。 为什么我的对象返回 nil? - I am trying to parse JSON from a subreddit with Swift Codable. Why are my objects returning nil? 为什么我的 UITableView 会出现 NSInternalInconsistencyException 异常? - Why am I getting an NSInternalInconsistencyException exception on my UITableView? 为什么我在IOS上获得Mapboxgl api的空白页? - Why I am getting blank page for Mapboxgl api on IOS? 一旦我登录,为什么我没有在 Swift 中将 HomeViewController 作为 Rootviewcontroller? - Once i Login why i am not getting HomeViewController as Rootviewcontroller in Swift? 为什么我收到“无法解析NSPredicate”错误 - Why am I getting a “Unable to parse NSPredicate” error 为什么我在 Xcode 10.1 中出现 swift 编译器错误 - Why I am getting swift compiler error in Xcode 10.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM