简体   繁体   English

Json 数据未显示在 tableView swift 5

[英]Json data not showing on tableView swift 5

I fetched the data and it is showing when printing but when i try to display it on tableview.Nothing is coming我获取了数据,它在打印时显示,但是当我尝试在 tableview 上显示它时。什么都没有

Am i placing tableview.reloadData in wrong place?我是否将 tableview.reloadData 放在错误的位置?

override func viewDidLoad() {
    super.viewDidLoad()
    fetchData()
    tableView.reloadData() 
}


func fetchData()
{     
    if let url = URL(string: urlConstant) {
       
        let session = URLSession(configuration: .default)
        let task = session.dataTask(with: url) { (data, res, err) in
       
            if err == nil
            {
                let decoder = JSONDecoder()
                if let safeData = data
                {
                    do{
                        let results = try decoder.decode(Results.self, from: safeData)
                        
                        guard let array = results.Result as? [Products] else {return }
                 
                        for product in array
                      {
    
                        self.productArray.append(product)
                        }
                     } catch {
                        print(error)
                    }                    
                }
            }
        }
        task.resume()            
    }
    
    self.tableView.reloadData()
}

If you are getting correct response(check it once) from the server then next thing you need to reload tableView after getting the response from the server and populating the array.如果您从服务器获得正确的响应(检查一次),那么接下来您需要在从服务器获得响应并填充数组后重新加载 tableView。

func fetchData() {
        if let url = URL(string: urlConstant) {
            let session = URLSession(configuration: .default)
            let task = session.dataTask(with: url) { (data, res, err) in
                if err == nil
                {
                    let decoder = JSONDecoder()
                    if let safeData = data
                    {
                        do{
                            let results = try decoder.decode(Results.self, from: safeData)
                            guard let array = results.Result as? [Products] else {return }
                            for product in array {
                              self.productArray.append(product)
                            }
                            // Reload table view here
                           DispatchQueue.main.async {
                            self.tableView.reloadData()
                          }
                        } catch {
                            print(error)
                        }
                    }
                }
            }
            task.resume()
        }
    }

Alternative, you can add completion handled in fetchData method.或者,您可以添加在 fetchData 方法中处理的完成。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM