Json data not showing on tableView swift 5

这一生的挚爱 提交于 2021-02-11 17:01:25

问题


I fetched the data and it is showing when printing but when i try to display it on tableview.Nothing is coming

Am i placing tableview.reloadData in wrong place ?

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()
}

回答1:


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.

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.



来源:https://stackoverflow.com/questions/62863848/json-data-not-showing-on-tableview-swift-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!