CompletionHandler is not executed

409 Views Asked by At

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)!
}
1

There are 1 best solutions below

2
On

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()
           }
        }
    })
}