1

In response to a user action, I would like to convert a CLLocation into an address string and display it back to the user.

The sequence is therefore 1. User action triggers sequence 2. ReverseGeocoder makes request to Apple's servers and returns results asynchronously. 3. Displays results to user.

I am able to display the results if I have a dedicated method with the display part in the completion block as follows:

  func userWantsAddress {        
    displayAddressFrom(location: myLocation)
    }
     func displayAddressFrom(location: CLLocation)  {
            CLGeocoder().reverseGeocodeLocation(location) { (placemark, error) in
                if error != nil {
                    print("error")

                } else {

                    let place = placemark! as [CLPlacemark]
                    if place.count > 0 {
                        let place = placemark![0]
                        var addressString : String = ""
                        if place.subThoroughfare != nil {
                            addressString = addressString + place.subThoroughfare! + "\n"
                        }
                        if place.thoroughfare != nil {
                            addressString = addressString + place.thoroughfare! + " in "
                        }

                        if place.locality != nil {
                            addressString = addressString + place.locality!
                        }

                        if place.subAdministrativeArea != nil {
                            addressString = addressString + ", "+place.subAdministrativeArea!
                        }
    //THIS IS WHERE YOU DISPLAY
                        myLabel.text = "THE LOCATION IS \(addressString)"
                        print("the location is",addressString)

                    }
                }
            }

        }

What I would like to do, however, is streamline the code so once the results are obtained, return them in a closure to the calling method for customization so that I can reuse the addressFromString method (and don't have to rewrite it every time I want to convert a location into an address) but I can't figure out the syntax.

I think I need to give the first method a completion block to wait for completion of the second. And have the second return results in a closure: Something like:

    func userWantsAddress(location: myLocation completion:@escaping (_ response:String)->()){

        displayAddressFrom(location: myLocation completion:completion) {

completion("HERE IS YOUR ADDRESS")
        }

However, I can't seem to get this right

Would be grateful for any suggestions on how to do this.

1 Answer 1

2

You just need to add a completion handler to your method and return the first placemark when calling completion:

func displayAddressFrom(location: CLLocation, completion: @escaping (CLPlacemark?, Error?) -> ())  {
    CLGeocoder().reverseGeocodeLocation(location) { 
        completion($0?.first, $1) 
    }
}

let location = CLLocation(latitude: -22.963451, longitude: -43.198242)
displayAddressFrom(location: location) { placemark, error in
    guard let placemark = placemark, error == nil else { return }
    // Update your UI from the main thread
    DispatchQueue.main.async {
        //  UI update here
        print(placemark)
    }
}

Morro da Saudade, Morro da Saudade, Rua Casuarina, 443, Lagoa, Rio de Janeiro - RJ, 22011-040, Brazil @ <-22.96345100,-43.19824200> +/- 100.00m, region CLCircularRegion (identifier:'<-22.96345100,-43.19824200> radius 141.83', center:<-22.96345100,-43.19824200>, radius:141.83m)


If you need a mailing string from your placemark you can get its postalAddress and create a string from it using CNPostalAddressFormatter string(for:) method:

import Contacts
extension CNPostalAddress {
    var mailingAddress: String {
        return CNPostalAddressFormatter.string(from: self, style: .mailingAddress)
    }
}

DispatchQueue.main.async {
    //  UI update here
    print(placemark.postalAddress?.mailingAddress ?? "")   // "Rua Casuarina, 443\nLagoa\nRio de Janeiro RJ\n22011-040\nBrazil"
}

Rua Casuarina, 443 Lagoa Rio de Janeiro RJ 22011-040 Brazil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.