我使用MapKit的CLGeocoder()。geocodeAddressString()来获取地址列表的坐标和县信息。只要请求数低于50,但任何超过50且达到API的限制,一切都很有效。由于CLGeocoder调用是异步的,我不能轻易地控制/控制调用流(例如,一次调用一个地址)。我如何在“异步世界”中正确地做到这一点? (免责声明:我是GCD和异步流控制领域的新手,所以我想我可能需要更详细的回复)
以下是相关代码:
在Property的地址上调用CLGeocoder的Class Property的方法:
func initializeCoordinates() {
let addressForCoords = self.address.getAddress()
CLGeocoder().geocodeAddressString(addressForCoords, completionHandler: { (placemarks, error) -> Void in
if error != nil {
print(error!)
return
}
if placemarks!.count > 0 {
let placemark = placemarks?[0]
let location = placemark?.location
self.coordinates = location?.coordinate
if let subAdminArea = placemark?.subAdministrativeArea {
self.address.county = subAdminArea
}
}
})
}
然后在ImportVC的部分中从textBox导入所有属性的地址(并在每个Property上调用initializeCoordinates
方法:
for line in importText {
let newAddress = Address()
let newHouse = Property()
// parse the tab delimited address for each line of input
let address = line.components(separatedBy: "\t")
if address.count == 4 {
newAddress.street = address[0]
newAddress.city = address[1]
newAddress.state = trimState(state: address[2])
newAddress.zip = address[3]
newHouse.address = newAddress
newHouse.initializeCoordinates()
houses.append(newHouse)
}
}
答案 0 :(得分:0)
我最近遇到了类似的问题。用最后调用自身的递归函数替换你的for循环。然而,诀窍是以0.2秒的延迟调用自己。我使用0.4来保证安全。这将增加用户的等待时间,但由于API限制我们别无选择。