Search code examples
swiftfunctionclgeocoder

How to make a function that return coordinates from address swift 4


Hi I want to receive the coordinates of an address. I made this function but not works. Return alway 0.0, 0.0

 func getCoordinates(address: String)->(Double, Double){
    DispatchQueue.main.async {
        let geoCoder = CLGeocoder()

        geoCoder.geocodeAddressString(address) { (placemarks, error) in
            guard let placemarks = placemarks, let location = placemarks.first?.location else {  return }
            latitude = location.coordinate.latitude
            longitude = location.coordinate.longitude

        }
    }
    return (latitude ?? 0.0, longitude ?? 0.0)

}

Solution

  • You need a completion and insert the main queue block inside the callback of the geocoder

    func getCoordinates(_ address: String,completion:@escaping((CLLocationCoordinate2D) -> ())){
        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(address) { (placemarks, error) in
            guard let placemarks = placemarks, let location = placemarks.first?.location else {  return }
            DispatchQueue.main.async {
                completion(location.coordinate)
            }
        }
    }
    

    call

    getCoordinates("someAdd") {  loc in
    
    }