iosswiftuitableviewmobile-application

Dynamically populating an iOS table view with Swift from an API


I'm currently in the process of creating an app to display the latest football scores. I've connected to an API through a URL and pulled back the team names for the english premier league into an array of strings.

The problem seems to come from populating the iOS table view that I intend to display the list of teams with. The data appears to be pulled from the API fine, but for some reason the TableView method which creates a cell and returns it doesn't seem to be called. The only time I can get the method to be called is when I actually hard code a value into the array of team names.

Here is my code:

class Main: UIViewController {

    var names = [String]()

    override func viewDidLoad() {

        super.viewDidLoad()

        let URL_String = "https://football-api.com/api/?Action=standings&APIKey=[API_KEY_REMOVED]&comp_id=1204"

        let url = NSURL(string: URL_String)

        let urlRequest = NSURLRequest(URL: url!)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)

        let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
            (data, response, error) in

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

                if let teams = json["teams"] as? [[String : AnyObject]] {
                    for team in teams {
                        if let name = team["stand_team_name"] as? String {
                            self.names.append(name)
                        }
                    }

                }
            } catch {
                print("error serializing JSON: \(error)")
            }

        })

        task.resume()
    }



    // Number of Sections In Table
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    // Number of Rows in each Section
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }

    // Sets the content of each cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel?.text = names[indexPath.row]
        return cell

    }

}

Just wondering if anyone can point me in the right direction here. This code doesn't crash or throw any errors, it just refuses to load a table view. The only reason I can possibly think of is that the array of team names is empty after completing a request to the API. However I've set breakpoints throughout and checked the values of local variables and the desired information is being pulled from the API as intended...


Solution

  • you are in the correct way , just refresh the table using reloadData once you got the new data from API

    if let teams = json["teams"] as? [[String : AnyObject]] {
                    for team in teams {
                        if let name = team["stand_team_name"] as? String {
                            self.names.append(name)
                        }
                    }
    
     dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.yourtableViewname.reloadData()
    })
      }