I am implementing forwardGeoLookup function, which looks up latitude and longitude for the given address name. I want to use the latitude and longitude outside the function and use it in detailViewController, but it keeps giving me only nil outside the function. It generates coordinates successfully in the function though.
How do I deal with this?
I have tried to create a variable in the function and use geocodeAddressString to generate coordinates and assigned to it. Then I returned then when the function is finished but still gave me nil.
extension MasterViewController: DetailViewControllerDelegate {
func forwardGeoLookup(_ address: String) {
// geo is an instance of CLGeocoder()
geo.geocodeAddressString(address) {placeMarks, error in
if error != nil {
print(error!)
}
if let placemark = placeMarks?.first {
guard let coordinate = placemark.location?.coordinate else {return}
let latitude = Double(coordinate.latitude)
let longitude = Double(coordinate.longitude)
let coordinates = (latitude,longitude)
self.detailViewController!.location = coordinates
}
}
}
class DetailViewController: UITableViewController {
var location: (Double,Double)?
override func viewWillDisappear(_ animated: Bool) {
self.delegate?.forwardGeoLookup(address)
guard let location = self.location else {return}
print(location.0)
}
super.viewWillDisappear(animated)
}
}
nil is printed when I print location.0. I want that to print latitude of the coordinate for the given address name.