TayaR
TayaR

Reputation: 31

Can't save data from geocoder to global variable

I've got weird problem. Im trying to geocode address from string and it works but I can only get data inside geocoder function. My code:

    private func getLocationFromAddress(address: String) -> CLLocationCoordinate2D{
    let geocoder = CLGeocoder()
    var lat = CLLocationDegrees()
    var long = CLLocationDegrees()
    geocoder.geocodeAddressString(address) { placemark, error in
        if let placemark = placemark{
            if let lattitude = placemark.first?.location?.coordinate.latitude, let longitude = placemark.first?.location?.coordinate.longitude{
                lat = lattitude
                long = longitude
                print(lat)
            }
        }else if let err = error{
            print(err.localizedDescription)
        }
    }
    print(lat)
    return CLLocationCoordinate2D(latitude: lat, longitude: long)
}

In this code when I print variable lat inside of geocoder it works, but when I try to print it outside it is 0.0. Why doesn't it work? Also 2nd print shows up earlier in console.

Upvotes: 0

Views: 68

Answers (1)

Eilon
Eilon

Reputation: 2982

Functions run synchronously, while geocodeAddressString(_:) is asynchronous. Use a closure as a completion handler instead.

private func getLocationFromAddress(address: String, completionHandler: @escaping (CLLocationCoordinate2D?) -> Void) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { placemark, error in
        if let placemark = placemark {
            if let lattitude = placemark.first?.location?.coordinate.latitude, let longitude = placemark.first?.location?.coordinate.longitude {
                let coordinate = CLLocationCoordinate2D(latitude: lattitude, longitude: longitude)
                completionHandler(coordinate)
            }
        } else if let err = error{
            print(err.localizedDescription)
            completionHandler(nil)
        }
    }
}

getLocationFromAddress(address: someAddress) { coordinate in
    if let coordinate = coordinate {
        print(coordinate.latitude)
        self.coordinate = coordinate
    }
}

Upvotes: 2

Related Questions