私はTableCellを作成する前にJSON呼び出しを取得しようとしていますが、ディスパッチキューを使用してコールブロックを作成することはできません。私はどのように私はそれがgroup.wait()
行で停止するように助言してください下に掲載されたコードです。JSON呼び出し後にディスパッチグループがブロックされない
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」をブロックすることは恐ろしいことです。恐ろしい使用経験があるからです。 JSONをviewDidLoad **に非同期的にロード**してから、テーブルビューをリロードしてください。 – vadian