Waffles Waffles - 2 years ago 66
Swift Question

PrepareForSegue is too fast for my other functions, and variables aren't updating in time?

I have a

that has a button. The button has an IBAction function, in which it calls
. The button is also a segue to a SECONDViewController.

The CLGeocoder inside the IBAction updates two variables, and those variables are passed in the prepareForSegue function.

However, since
acts asynchronously, it is too slow to update the variables before the segue occurs, and thus, the incorrect variables are being passed to the
. How could I fix this?

Here's the code in my IBAction method:

geocoder.geocodeAddressString(userInputText!) { (placemarks, error) -> Void in
if let firstPlacemark = placemarks?[0] {
self.searchLatitude = "\(firstPlacemark.location!.coordinate.latitude)"
self.searchLongitude = "\(firstPlacemark.location!.coordinate.longitude)"
self.addressLoaded = true
} else {
//implement error pop up

Answer Source

All the CLGeocoder instance methods accept a completionHandler parameter. Try to call the performSegue from it

EDIT: this is an example

@IBAction private func buttonPressed(sender: UIButton?) {

    let geoCoder = CLGeocoder()

        "Your address string") { (let placeMarks, let error) in

            if let error = error {

                // handle the error

            } else if let placemarks = placeMarks {

                // Do whatever with the placemarks
                    "Segue identifier",
                    sender: sender
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download