在异步方法中准备数据后,如何为tableview重新加载数据 [英] How to reloadData for tableview after data been prepared in a asynchronously method
问题描述
我使用 URLSession
从tableview'data的资源API获取数据。因此,在URLSession任务准备好数据后,我需要 reloadData()
。但这将导致,
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()必须仅在主线程中使用
UITableView.reloadData() must be used from main thread only
当我运行应用程序时,开始时tableview为空白。只有在我屏幕显示数据后才会显示。但如果不在URLSession任务中调用 reloadData()
,则屏幕一直是空白。
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()
}
推荐答案
你永远不应该从后台线程访问任何UI,你必须从主线程中执行它,为此你可以使用gcd:
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()
}
虽然从后台线程访问UI(读取所有UIKit)可能有时会工作,但最终会出现包括崩溃,炸毁显示或gazenbugs在内的错误。
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.
这篇关于在异步方法中准备数据后,如何为tableview重新加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!