我使用mapkit的clgeocoder().geocodeaddressstring()获取地址列表的坐标和县信息。只要请求的数量在50以下,一切都会很好。但如果超过50,我就会达到api的极限。由于clgeocoder调用是异步的,所以我无法轻松地限制/控制调用流(例如,一次调用一个地址)。在“异步世界”中,我应该如何正确地做到这一点?(免责声明:我对gcd和异步流控制还不熟悉,所以我想我可能需要更详细的响应)
以下是相关代码:
在属性的地址上调用clgeocoder的类属性的方法:

   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中从文本框导入所有属性地址的部分(并对每个属性调用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)
        }
    }

最佳答案

我最近也遇到过类似的问题。用在末尾调用自身的递归函数替换for循环。但是诀窍是用0.2秒的延迟来调用它自己。我用0.4是为了安全起见。这将增加用户的等待时间,尽管由于api的限制,我们没有选择。

关于swift - CLGeocoder geocodeAddressString()达到极限,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42229562/

10-16 11:03