Die geocodeAddressString
läuft asynchron (dh auch wenn das Verfahren zu einem anderen Viewcontroller analysieren kehrt sofort zurück, seine completionHandler
Schließung kann später aufgerufen werden). Also, bist du sicher, dass es sich nicht ändert oder sich einfach nicht ändert, wenn du versuchst chooseCoordinates
zu benutzen? Sie sollten jede Aktualisierung der Benutzeroberfläche oder was auch immer aus der Schließung (oder der didSet
von chooseCoordinates
) initiieren, nicht sofort tun. Wir sehen nicht, wie Sie chooseCoordinates
verwenden, so dass es schwieriger ist, genauer zu sein.
Zum Beispiel:
geocoder.geocodeAddressString(sender.text!) { placemarks, error in
if error != nil {
print(error!)
}
if let placemark = placemarks?.first {
let coordinates: CLLocationCoordinate2D = placemark.location!.coordinate
self.chooseCoordinates = coordinates
// call the method that uses `chooseCoordinates` here
}
}
// don't try to use `chooseCoordinates` here, as it hasn't been set yet.
Oder vielleicht verwenden Sie das completionHandler
Muster selbst:
@IBAction func didEndEditingTextField(sender: UITextField) {
geocodeAddressString(sender.text!) { coordinate, error in
self.chooseCoordinates = coordinate
// trigger whatever the next step is here, or in the `didSet` of `chooseCoordinates`
}
// don't try to use `chooseCooordinates` here
}
var chooseCoordinates: CLLocationCoordinate2D? // you probably should make this optional
let geocoder = CLGeocoder()
/// Geocode string
///
/// - parameter string: The string to geocode.
/// - parameter completionHandler: The closure that is called asynchronously (i.e. later) when the geocoding is done.
func geocodeAddressString(string: String, completionHandler: (CLLocationCoordinate2D?, NSError?) ->()) {
geocoder.geocodeAddressString(string) { placemarks, error in
if error != nil {
print(error!)
}
if let placemark = placemarks?.first {
completionHandler(placemark.location!.coordinate, error)
} else {
completionHandler(nil, error)
}
}
}
Thank you! Ich benutzte das erste in meinem anderen View-Controller und es funktionierte, also ging es wirklich um Synchronisation. –