swift - iOS - How can I return latitude and longitude? -
i can't return latitude , longitude. 0.0 , 0.0.
what can these values?
code :
func forwardgeocoding (address: string) -> (double, double) { let geocoder = clgeocoder() var latitude: double = 0.0 var longitude: double = 0.0 geocoder.geocodeaddressstring(address) { (placemarks: [clplacemark]?, error: nserror?) -> void in if error != nil { print(error?.localizeddescription) } else { if placemarks!.count > 0 { let placemark = placemarks![0] clplacemark let location = placemark.location latitude = double((location?.coordinate.latitude)!) longitude = double((location?.coordinate.longitude)!) print("before : \(latitude, longitude)") } } } print("after : \(latitude, longitude)") return (latitude, longitude) }
this viewdidload:
override func viewdidload() { super.viewdidload() forwardgeocoding("new york, ny, united states") }
result:
after : (0.0, 0.0)
before : (40.713054, -74.007228)
the problem code geocoding requests asynchronous, return
statement executed before geocoding results retrieved.
i'd use 1 of 2 options fix this. first, instead of returning tuple, make own completion handler, , call after placemark found:
func forwardgeocoding (address: string, completion: (cllocationcoordinate2d) -> void) { let geocoder = clgeocoder() geocoder.geocodeaddressstring(address) { (placemarks: [clplacemark]?, error: nserror?) -> void in if error != nil { print(error?.localizeddescription) } else { if placemarks!.count > 0 { let placemark = placemarks![0] clplacemark let location = placemark.location completion(location.coordinate) } } } }
now when call function can provide completion relevant values wherever you're calling function.
if function method in class , never needs called class, have set properties of class, , properties have didset
blocks. example:
class someclass { var coordinates: cllocationcoordinate2d { didset { dosomethingwithcoordinates() } } private func forwardgeocoding (address: string, completion: (cllocationcoordinate2d) -> void) { let geocoder = clgeocoder() geocoder.geocodeaddressstring(address) { (placemarks: [clplacemark]?, error: nserror?) -> void in if error != nil { print(error?.localizeddescription) } else { if placemarks!.count > 0 { let placemark = placemarks![0] clplacemark let location = placemark.location self.coordinates = location.coordinate } } } } }
the first options more versatile, second avoids having completion blocks withing completion blocks, can become confusing keep track of in code.
Comments
Post a Comment