Loan Loan -3 years ago 190
Swift Question

iOS - Wait for a query to be completed

I have a table that displays the results of an http request.
Sometimes the application crashes because the table is displayed before the query is finished .. How can the application no crash?

The table :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCustomCell
for i in 0...nameOfRoutesStart.count {
if (indexPath.row == i) {
cell.originLabel.text = nameOfRoutesStart[i]
cell.destinationLabel.text = nameOfRoutesEnd[i]
let id = driver[i]
self.userTasks.user(driverId: id, completionHandler: { (status, success) -> Void in
if success {
cell.driverLabel.text = self.userTasks.username
}
})
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
}
}
return cell
}


I make the request in another function
Thanks

Answer Source

Extract your asynchronous code from the tableview methods to your viewDidLoad. Save the data you retrieve in a variable declared in your controller and call .reloadData() on your tableview when your fetch is finished.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download