Zhandos.Nurakhmetov
Zhandos.Nurakhmetov

Reputation: 169

swift: Completion handler

So, I have method loadData() which download datas from parse.com

enter image description here

And I should present all images show in table view.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("ReusableCell", forIndexPath: indexPath) as! LeaguesTableViewCell

    loadData { (success) in
        if success {
            cell.leagueImage.image = UIImage(data: self.leaguesImage[indexPath.row])
            cell.leagueNameLabel.text = self.leagues[indexPath.row]["name"] as? String
        } else {
            cell.leagueNameLabel.text = "Wait"
        }
    }


    return cell

}

Its didn't work. I call my function in viewDidLoad() but its not correct too, table view is empty.

enter image description here Cuz my array is empty

My

Upvotes: 2

Views: 1006

Answers (2)

Luke Van In
Luke Van In

Reputation: 5265

The basic procedure for loading data into a UITableView is:

  1. Load the data
  2. Reload the table view
  3. Return the number of sections in numberOfSectionsInTableView: method: In your case there is only 1 section.
  4. Return the number of rows in tableView:numberOfRowsInSection:: In your case return the number of leagues if the data is loaded. If the data is not loaded then return 1 so that the table view has at least one row to display the "Wait" message.
  5. Create and populate the cells from the data: Use leagues and leaguesImage.

Example:

private var loaded = false   

override func viewDidLoad() {
    super.viewDidLoad()

    loaded = false

    loadData() { success in
        NSOperationQueue.mainQueue().addOperationWithBlock() {
            self.loaded = success
            self.tableView.reloadData()
        }
    }
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection: Int) -> Int {
    if loaded {
        return leagues.count 
    }
    else {
        return 1
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("ReusableCell", forIndexPath: indexPath) as! LeaguesTableViewCell

    if loaded {
        cell.leagueImage.image = UIImage(data: self.leaguesImage[indexPath.row])
        cell.leagueNameLabel.text = self.leagues[indexPath.row]["name"] as? String
    }
    else {
        cell.leagueNameLabel.text = "Wait"
    }

    return cell
}

Upvotes: 3

Arsalan
Arsalan

Reputation: 170

Try to set delegate and datasource first. If you have separate datasource other than view controller, retain it otherwise you will not get any callback.

Upvotes: 1

Related Questions