CLGeocoder地理编码请求超过限制

时间:2016-04-25 17:50:23

标签: ios swift clgeocoder

我试图找出限制我对CLGeocoder的请求数量的方法,因为我一直在超过最大限制。我得到" 错误域= kCLErrorDomain Code = 2"(null)"。基本上,每当有人在func regionDidChangeAnimated中移动地图时,我得到他们所依赖的坐标,地理编码以获取城市/州,然后点击我的API,然后使用这些结果对该区域中的新地图引脚进行地理编码。有没有人有任何最佳做法来处理这种情况?非常感谢任何帮助。

查看用户是否更改了地图区域的功能:

private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view: UIView = self.mapView.subviews[0] as UIView
//  Look through gesture recognizers to determine whether this region change is from user interaction
if let gestureRecognizers = view.gestureRecognizers {
    for recognizer in gestureRecognizers {
        if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
            return true
        }
    }
 }
  return false
}

func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
if (mapChangedFromUserInteraction) {
    // user changed map region

   }
}

func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if (mapChangedFromUserInteraction) {
    // user changed map region
    let center = mapView.centerCoordinate

    let mapLatitude = center.latitude
    let mapLongitude = center.longitude


     let locationmove = CLLocation(latitude: mapLatitude, longitude: mapLongitude)
    CLGeocoder().reverseGeocodeLocation(locationmove) { (placemarks, error) in

        if (error != nil){

            print(error)

        }else {

            if let p = placemarks?[0]{

                let locality = p.locality ?? ""
                let administrativeArea = p.administrativeArea ?? ""


                 self.mappedCity = String(locality)
                 self.mappedState = String(administrativeArea)
                 self.parseJSON("\(locality)", state: "\(administrativeArea)")
            }

        } 

     }
   }
  }

从地理编码结果解析JSON的函数:

func parseJSON(city: String, state: String){
let passedCity = city
let passedState = state
let escapedCity = passedCity.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let escapedState = passedState.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

let url = NSURL(string:"http://www.API.com/api.php?city=\(escapedCity)&stateAbv=\(escapedState)&limit=10”)!

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url) { (items, response, error) -> Void in

    if error != nil {

        print(error)


    }else {


        if let items = items {


            do {
                let jsonResult = try NSJSONSerialization.JSONObjectWithData(items, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                if jsonResult.count > 0 {

                    if let datas = jsonResult["data"] as? NSArray{

                        for data in datas{

                            if let title = data["title"] as? String {

                                if let street = data["street"] as? String {

                                    if let city =  data["city"] as? String {

                                        if let stateAbv =  data["stateAbv"] as? String {

                                            if let zip =  data["zip"] as? String {

                                                self.geoAddress("\(title)", street: "\(street)", city: "\(city)", state: "\(stateAbv)", zip: "\(zip)")


                                            }
                                        }
                                    }

                                }

                            }

                        }
                    }

                }
            } catch{}


        }


    }

 }

 task.resume()

}


func geoAddress(title: String, street: String, city: String, state: String, zip: String){
let storeName = "\(title)"
let location = "\(street) \(city) \(state) \(zip)"
let geocoder = CLGeocoder();
geocoder.geocodeAddressString(location, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
    if (error != nil) {
        print("Error \(error!)")
    } else if let placemark = placemarks?[0] {

        let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

        let pointAnnotation:MKPointAnnotation = MKPointAnnotation()
        pointAnnotation.coordinate = coordinates
        pointAnnotation.title = storeName
        pointAnnotation.subtitle = location

        self.mapView.addAnnotation(pointAnnotation)

     }
  })
}

1 个答案:

答案 0 :(得分:0)

只需将更新后的位置与旧位置进行比较,因此您获得的距离应足够高,以便发出另一个CLGeocoder请求。 Apple的文档说明了

  • 如果要自动更新用户的当前位置 (例如当用户移动时),仅发出新的地理编码请求 当用户移动了很长的距离并且在合理的时间之后 时间已经过去了。例如,在典型的情况下,你 不应每分钟发送多个地理编码请求。

    查看CLGeocoder的官方文档以获取更多信息。