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:
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.
Try this
You can't do any UI update operation in background thread. So can put it in main thread.
If you try to perform UI operation in background thread it will cause crash.
The best way to Update UI Views .. Use main queue.
I hope it will work.