Search code examples
iosjsonswift

Populating Table from JSON


I'm getting some JSON data from an API and I want to put them in a tabel. I have declared a global array to store the JSON in it and then put that array in a table.

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
    if let parseJSON = json
    {
        let IDD = parseJSON["categoryList"] as AnyObject
        let userID = IDD.value(forKey: "goodTypeName")
        print(userID as Any)

        Global.GlobalVariable.names = userID as! [String]
        print(Global.GlobalVariable.names)

The above code shows just part of my code that I'm saving the JSON in Global.GlobalVariable.names.

class Global: UIViewController
{
    struct GlobalVariable
    {
        static var names  = ["2" , "2" , "3","4","5","6","7","8","9"]
    }
}

The above code is my global var.

When I'm going to populate the table with the JSON data that I have saved in my array, it shows the array's original data (1,2,3..).

But when I scroll the page, the data that I need will then show up. Cells only get the data after scrolling.


Solution

  • You need to reload , it shows when you scroll as the model is updated and old data shown becomes on the fly , when you scroll cellForRowAt is called and it fetches the new data

    Global.GlobalVariable.names = userID as! [String]
    DispatchQueue.main.async {
      self.tableView.reloadData()
    }