0

In our code, we call a method that supposedly returns the address of the current device's location from the CLGeocoder. But the problem is the CLGeocoder performs the request asynchronously and calls the completionHandler when it's done so there's a "delay".

Is there a way to perform the reverseGeocodeLocation and return the result within the method? So basically the method that is being called needs to "wait" until the CLGeocoder's request is done.

SquareBox
  • 823
  • 1
  • 10
  • 22

1 Answers1

-1
func findGMSAddress(completion : @escaping (_ address : LocationModel)->()) {

    let geoCoder = CLGeocoder()
    let loca = CLLocation(latitude: self.location.latitude, longitude: self.location.longitude)
    geoCoder.reverseGeocodeLocation(loca) { (placemarks, error) -> Void in

        if error != nil {
            print("Error getting location: \(String(describing: error))")
        } else {
            let placeArray = placemarks as [CLPlacemark]!
            var placeMark: CLPlacemark!
            placeMark = placeArray?[0]
            self.location.name = placeMark.name ?? ""
            self.location.adminArea = placeMark.administrativeArea ?? ""
            self.location.locality = placeMark.locality ?? ""
            self.location.thoroughFare = placeMark.thoroughfare ?? ""

            completion(self.location)
        }
    }

}

use above method like this :

  // show loader
  self.findGMSAddress(completion: { (address) in
       DispatchQueue.main.async {
            // hide loader

            // use address here
      }
  })
  • thanks for the response, unfortunately we already tried this and we don't think this works the way we want it. The problem with this is that the request happened in the background thus the method already return an empty string before the request is done. – SquareBox Jan 10 '18 at 00:37
  • I had have the same problem with you. I tried KVO to catch up the response when the request location completely done. – Cuong Nguyen Aug 26 '19 at 08:12