Waffles Waffles - 7 months ago 18
Swift Question

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

I have a

FIRSTViewController
that has a button. The button has an IBAction function, in which it calls
CLGeocoder()
. 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
CLGeocoder
acts asynchronously, it is too slow to update the variables before the segue occurs, and thus, the incorrect variables are being passed to the
SECONDViewController
. 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
print("error")
}
}

Answer

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()

    geoCoder.geocodeAddressString(
        "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
                self.performSegueWithIdentifier(
                    "Segue identifier",
                    sender: sender
                )
            }
    }
}
Comments