I use URLSession to get data from a resource API for tableview'data. So I need to reloadData() after data prepared by the URLSession task. But this will lead to,
UITableView.reloadData() must be used from main thread only
And when I run the app, at begin the tableview is blank. Only after I croll the screen the data will show. But if not call reloadData() in the URLSession task, the screen is blank all the way.
func getData() {
let dataUrl = URL(string: "http://www.example.com/app/?json=1")
let task = URLSession.shared.dataTask(with: dataUrl! as URL) {data, response, error in
guard let data = data, error == nil else { return }
do {
self.data = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
self.tableView.reloadData()
}
} catch let error {
print(error)
}
}
task.resume()
}
You should never access any UI from background threads, you must do it from the main thread, to do this you may use gcd:
DispatchQueue.main.async {
self.tableView.reloadData()
}
While accessing UI (read everything UIKit) from background thread may work sometimes, you'll end up with bugs including crashes, blown up display or gazenbugs.
You can't do any UI update operation in background thread. So can put it in main thread.
DispatchQueue.main.async {
tableView.reloadData()
}
If you try to perform UI operation in background thread it will cause crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With