ios - 无法让 API 调用及时运行 tableview swift 4 xcode 9
问题描述
我正在尝试获取 API 调用来填充列表视图的单元格,但似乎无法在生成单元格之前获取要收集的数据。我已经尝试过像这里一样制作完成处理程序以及来自同一链接的信号量,但无济于事。编译完成处理程序时,它在执行时仍然没有及时获取数据(诚然,这是我第一次尝试完成处理程序)。这是没有完成处理程序的原始代码:
override func viewDidLoad() {
super.viewDidLoad()
RestaurantListView.delegate = self
RestaurantListView.dataSource = self
//API setup
guard let url = URL(string: "https://myURL.com") else {
print("ERROR: Invalid URL")
return
}
let task = URLSession.shared.dataTask(with: url) {
(data, response, error) -> Void in
// URL request is complete
guard let data = data else {
print("ERROR: Unable to access content")
return
}
guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
print("Error: Couldn't decode data into Blog")
return
}
self.myData = blog
}
task.resume()
}
表格和单元格在这些函数下方初始化:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = RestaurantListView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = myAPIValue
return cell!
}
我有几个打印语句来跟踪程序,它通过 viewDidLoad 然后第一个 tableView 设置表格然后第二个处理单元格,最后它通过 URL 任务。
我已经重写了几十种不同的方式,但不知道如何让它以正确的顺序执行。
解决方案
您需要重新加载表,因为此行URLSession.shared.dataTask(with: url)
触发了一个异步任务,该任务与您的代码行的顺序不同
guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
print("Error: Couldn't decode data into Blog")
return
}
self.myData = blog
DispatchQueue.main.async{
RestaurantListView.reloadData()
}
推荐阅读
- php - Mysql查询加入数据并按顺序显示
- sql-server - 无法在 SQL Server 的 xml 路径中传递表列名称
- json - 在 map[string]interface{} 的值上键入 switch to []map[string]interface{}
- forms - Xamarin WebView 未加载来自 webrtc 的流
- python - 在 Python 速成课程练习中数小时无法解决 NameError
- c# - XMLSerializer 找到未知节点
- php - 保护 Markdown 生成的 HTML 上的 XSS
- azure-sdk-.net - 从存储在另一个存储帐户中的 VHD 创建 OS 磁盘
- bash - 如何仅获取 bash ssh 版本号?
- javascript - 如何将数据从 api 推送到数据集中