First I have a global variable:
var userCity : String?
Using reverseGeocodeLocation() to obtain the city name from the user's location, I am trying to store that city name information into the userCity global variable. I know that you cannot simply return data from asynchronous tasks. Instead, you would have to pass back via a block. This is what I have so far after looking at other StackOverflow posts:
//get user's location
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
reverseCoordinatesToCity(location: location) { (city) in
self.userCity = city
}
}
}
func reverseCoordinatesToCity(location: CLLocation, completion: @escaping (_ city: String?) -> Void) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if (error != nil) {
print("Reverse geocoder failed with an error: " + (error?.localizedDescription)!)
completion("")
} else if (placemarks?.count)! > 0 {
let pm = placemarks![0] as CLPlacemark
completion(pm.locality!)
} else {
print("Problems with the data received from geocoder.")
completion("")
}
})
}
When I try to print userCity in a different method. For example:
func someFunction() {
print(userCity!)
}
Nothing is printed out and it seems that userCity is nil. I've spent almost three hours trying to figure this out. My main goal is to pass this data onto another ViewController using a segue.
Any help is appreciated. Thank you.