我正在使用循環並對CLGeocoder進行API調用。 API調用正確的次數,但completionHandler只返回一次,用於第一次API調用,然後它不會爲其餘調用返回任何內容。API調用僅在循環中返回響應一次
dispatch_async(dispatch_get_main_queue())
{
for shop in self.shopsList {
let shopAddress = shop.address
self.geocoder.geocodeAddressString(shopAddress, completionHandler: { (placemarks, error) in
if let error = error {
print(error)
return
}
if let placemarks = placemarks where placemarks.count > 0 {
if let location = placemarks.first?.location {
print("The longitude: \(location.coordinate.longitude)")
print("The latitude: \(location.coordinate.latitude)")
}
}
})
}
self.spinner.dismiss()
self.categoryTableView.dataSource = self
self.categoryTableView.delegate = self
self.categoryTableView.reloadData()
}
其餘調用根本不返回任何內容,甚至不輸入任何if語句。有人能告訴我我做錯了什麼嗎?
我曾試過把的結束for循環增加sleep(2)
,但它仍然只能返回一次
我曾嘗試在for循環的末尾添加'sleep(2)',但它仍然只返回一次 – Bob
使用sleep幾乎從來都不是一個好主意,特別是從主線程中。 rmaddy在他的回答中包含了關於如何執行多個地址解析請求的建議鏈接。至少,您需要重構代碼以提交請求並等待它完成,然後再提交下一個請求。 –
使用睡眠(2)是建議我知道的建議 – Bob