-1

I am trying to create function which can return CLLocation value?

As this is asynch method it gives value after some time and return get called before that. is there any way to return after getting lat, lon?

func setLocation(location: String) -> [String]{
            var lat: CLLocationDegrees?
            var lon: CLLocationDegrees?
            geocoder.geocodeAddressString(location) { placemarks, error in
                let placemark = placemarks?.first
                lat = placemark?.location?.coordinate.latitude
                lon = placemark?.location?.coordinate.longitude
                print("Lat: \(lat), Lon: \(lon)") //here i get value
            }

            print("Lat: \(lat), Lon: \(lon)") //but here i get nil

            return ["\(String(describing: lat))", "\(String(describing: lon))"]

        }
New iOS Dev
  • 1,937
  • 7
  • 33
  • 67

1 Answers1

0

Use a completion

func setLocation(location: String,completion:@escaping(CLLocationCoordinate2D? -> ())) {
            var lat: CLLocationDegrees?
            var lon: CLLocationDegrees?
            geocoder.geocodeAddressString(location) { placemarks, error in
                let placemark = placemarks?.first
                completion(placemark?.location?.coordinate) 
            }
}

setLocation(location: "") { (coor) in
   print(coor.latitude)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87