VaperLife
VaperLife

Reputation: 13

Swift get String from completionHandler

import Foundation
import CoreLocation

class Converters  {
private var coordinate: String = ""
let geocoder = CLGeocoder()
func CityToCoordinate(city: String) ->String {
    geocoder.geocodeAddressString(city, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
        if((error) != nil){
            print("Error", error)
        }
        if let placemark = placemarks?.first {
            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
            self.coordinate = "\(coordinates.latitude),\(coordinates.longitude)"
            print(self.coordinate) //Here, I get the value: 47.7845996,19.1310416
        }
    })
    print(coordinate) //Has no value, but I need the same: "47.7845996,19.1310416"
    return coordinate // Don't return anything, I set in geocoder
}


}

Image

Any solution? I want to get the String from the completionHandler event, I need the coordinates to return.

Upvotes: 1

Views: 522

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Add the completion handler to the CityToCoordinate signature:

completion: (string: String)->()

and use it where the data is available.

Like this:

class Converters  {
    private var coordinatese: String = ""
    let geocoder = CLGeocoder()

    func CityToCoordinate(city: String, completion: (string: String)->()) {
        geocoder.geocodeAddressString(city, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
            if((error) != nil){
                print("Error", error)
            }
            if let placemark = placemarks?.first {
                let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
                self.coordinatese = "\(coordinates.latitude),\(coordinates.longitude)"

                completion(string: self.coordinatese)
            }
        })
    }
}

And call it with a trailing closure:

let conv = Converters()
conv.CityToCoordinate("Paris") { (string) in
    print(string)  // 48.8567879,2.3510768
}

Upvotes: 1

Related Questions