【发布时间】:2016-12-10 20:07:25
【问题描述】:
我试图在填充 TableCell 之前让我的 JSON 调用返回,但是作为 swift 的新手,我无法使用调度队列来阻止调用....谁能告诉我如何让它停止在下面发布的代码中的group.wait() 行。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let queue:DispatchQueue = DispatchQueue.global()
let group:DispatchGroup = DispatchGroup()
Alamofire.request("http://localhost:3000/locations.json").responseJSON { response in
group.enter()
//print(response.request) // original URL request
//print(response.response) // HTTP URL response
//print(response.data) // server data
//print(response.result) // result of response serialization
guard response.result.error == nil else{
print("Error: unable to get a list of locations.")
return
}
if let JSON = response.result.value {
// print("JSON: \(JSON)")
if let result = response.result.value as? [[String: Any]] {
nameArray = result.map { ($0["name"] as? String)! }
print(nameArray[0])
}
}
group.leave()
}
group.notify(queue: queue) {
// This closure will be executed when all tasks are complete
print("All tasks complete")
}
// synchronize on task completion by waiting on the group to block the current thread.
print("block while waiting on task completion")
let _ = group.wait()
print("continue")
let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
cell.textLabel?.text = LocationData[indexPath.row].name
print (LocationData[indexPath.row].name)
print(indexPath.row)
// cell.textLabel?.text = nameArray[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.selectedImage = pictures[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
【问题讨论】:
-
强烈建议您不要屏蔽
cellForRowAt,因为您将获得糟糕的使用体验。 异步在 viewDidLoad 中加载 JSON,然后重新加载表格视图。
标签: swift uitableview grand-central-dispatch alamofire