DCDC DCDC - 2 months ago 34
Swift Question

Swift 3: reverseGeocodeLocation does not its completion handler

This is my code

if loc.latitude != 0.0 && loc.longitude != 0.0 {
let loca = CLLocation(latitude: loc.latitude, longitude: loc.longitude)
geoCoder.reverseGeocodeLocation(loca) { (placemarks, error) in // this is the last line that is being called
var placemark : CLPlacemark!
placemark = placemarks?[0]
city = (placemark.addressDictionary?["City"] as! String)
}
}


Execution of this code snippet in my app goes right, no runtime errors occurred.

However, the last line that is being called is

geoCoder.reverseGeocodeLocation(loca){(placemarks, error)


I also double checked that
loca
is not nil.

Why completion handler is not being called?

Answer

Use completionHandler in Closure.

Check below example:

geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

            // Place details
            var placeMark: CLPlacemark!
            placeMark = placemarks?[0]

            // Address dictionary
            print(placeMark.addressDictionary, terminator: "")

            // Location name
            if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
                print(locationName, terminator: "")
            }

            // Street address
            if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
                print(street, terminator: "")
            }

            // City
            if let city = placeMark.addressDictionary!["City"] as? NSString {
                print(city, terminator: "")
            }

            // Zip code
            if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
                print(zip, terminator: "")
            }

            // Country
            if let country = placeMark.addressDictionary!["Country"] as? NSString {
                print(country, terminator: "")
            }

        })