Motivation gym5
Motivation gym5

Reputation: 291

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

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

Upvotes: 0

Views: 97

Answers (1)

Shashank Mishra
Shashank Mishra

Reputation: 1079

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.

Upvotes: 1

Related Questions