我有以下无错误的代码,似乎无法使用我的结果数组的任何信息。玩完之后,我可以打印列出的每个businessID位置,但我无法添加/使用用于保存此信息的数组。我不明白为什么每个位置都会打印,但我的数组显示为空。
我为我的整个代码道歉,但我花了好几个小时试图纠正我的问题......
import UIKit
import GooglePlaces
class FoodTwo: UITableViewController {
var placesClient: GMSPlacesClient!
let international: [String] = ["ChIJAQDABX7CIogRIEY3k6r7R-g",
"ChIJqX3q1IbCIogRFcuI05IPNDU",
"ChIJAQDABX7CIogRY2MA6XVas8E"]
let american: [String] = ["ChIJkX9tTSvoIogROXkxd0gpg3s", "ChIJy7lUZCfoIogRVBuB9jWKHUk", "ChIJyzCZMiroIogRkuMavnKsA0w", "ChIJbYvWJ5jCIogRxh0VQA_yD0I", "ChIJa4Sks23CIogRpRod4v5GEN8", "ChIJxVpGsNbpIogRG5HIAKbNyDU", "ChIJ1W32UyvoIogRyp_Rdxn6f8I", "ChIJwTht4ifoIogRsuXdEOrKGMk", "ChIJ6UXEgNPpIogR4Q3ZAAWQQSI", "ChIJUZVAjdTpIogRpyca26a6D8o", "ChIJ6-h6_EctIIgRO1kypozaGGs", "ChIJK8NGam7CIogRlzU1TKeSjVI", "ChIJ7Xxh1m3CIogRZ_yabslUzd8", "ChIJ_dxSGJ7CIogRcYwJhjAm7TQ"]
// more arrays here - deleted to reduce scrolling//
var results = [GMSPlace]()
var index: IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
var place: [String]
switch index.row
{
case 0 :
place = international
case 1 :
place = american
case 2 :
place = asian
case 3 :
place = bakery
case 4 :
place = bar
case 5 :
place = indian
case 6 :
place = italian
default :
place = mexican
}
for id in place
{
placesClient.lookUpPlaceID(id, callback: { (result, error) -> Void in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
guard let result = result
else
{
print("No place details for \(id)")
return
}
self.results.append(result)
})
OperationQueue.main.addOperation( { () -> Void in
self.tableView.reloadData()
})
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FCT") as! FoodCellTwo
let each = results[indexPath.row]
cell.nameLabel.text = each.name
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:1)
placesClient.lookUpPlaceID
是异步功能。你必须等到它完成。因此,在数组填充之前,您正在重新加载表视图。
您应该在数组填满后重新加载表格视图。
for id in place {
placesClient.lookUpPlaceID(id) { result, error in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
guard let result = result else {
print("No place details for \(id)")
return
}
self.results.append(result)
if place.count == self.results.count {
self.tableView.reloadData()
}
}
}