-1

Im trying to obtain the "locality" from Coordinates using CLGeocoder.reverseGeocodeLocation, but when the execution reach the completionHandler the code inside the bracket is completely skipped to self.currentPlace = (self.place?.locality)! + ", " + (self.place?.thoroughfare)! freezing the application.

where am I wrong??

func updateLocation() {
    let location = CLLocation.init(latitude: currentCoordinates.latitude, longitude: currentCoordinates.longitude)
    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error)  in
        if (error != nil) {
            print("Error")
        }else {
        let pm = placemarks as [CLPlacemark]!
        if pm.count > 0 {
        self.place = pm.first
        self.stopUpdatingLocation()
           }
        }
    })
    self.currentPlace = (self.place?.locality)! + ", " + (self.place?.thoroughfare)!
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
Swalsz
  • 33
  • 3

1 Answers1

0

This is called asynchronous programming. The completion handler is called after a while when the reverse geocode has completed. You need to call the UI update inside the handler.

You can show some sort of loader which indicates to the user that an operation is in progress.

func updateLocation() {
    let location = CLLocation.init(latitude: currentCoordinates.latitude, longitude: currentCoordinates.longitude)
    let geocoder = CLGeocoder()

    //Show loader here
    geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error)  in
        //hide loader here
        if (error != nil) {
            print("Error")
        }else {
        let pm = placemarks as [CLPlacemark]!
        if pm.count > 0 {
        self.place = pm.first
        self.currentPlace = (self.place?.locality)! + ", " + (self.place?.thoroughfare)!
        self.stopUpdatingLocation()
           }
        }
    })
}
ZeMoon
  • 20,054
  • 5
  • 57
  • 98
  • Thank you. I added a loader as you suggested but the situation does not changed. I solved deleting the variable "currentPlace" and replacing it with the Label i would fill. – Swalsz Feb 09 '16 at 14:09
  • There was too much passing data. Thank you anyway – Swalsz Feb 09 '16 at 14:16