Search code examples
iosswiftuitableviewios9

Filling UITableView cell from remote database


I am facing an issue with UITableView.

I want to dynamically fill its cells with data fetched from a remote database, so it takes some times before the data arrived.

Here is the code:

class MailBoxViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var users: [NSDictionary] = []

override func viewDidLoad() {
    super.viewDidLoad()

    // call to rest API code to get all users in [NSDictionary]
    (...)

    // set table view delegate and data source
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

// set number of sections within table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

// set number of rows for each section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return self.users.count
    }
    return 0
}

// set header title for each section
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "Users"
    }
}

// set cell content for each row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // deque reusable cell
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

    // set item title
    if indexPath.section == 0 {
        cell.textLabel?.text = self.users[indexPath.row]["firstname"] as? String
    }
    return cell
}
}

The problem is that when tableView functions are called to set number of rows for each section and to set cell content for each row, my [NSDictionary] users is still empty.

How could I do to set rows and cells only after my call to rest API code to get all users in [NSDictionary] is finished?

Thank you for any feedback.

Regards


Solution

  • When you get the response from the API, you should set self.users = arrayOfUsersYouReceivedFromServer and then call self.tableView.reloadData(). This