I'm still learning to code so please don't shoot me for asking a question. I have tried to find an answer however I haven't found anything on stack overflow that can help, nor within a couple of books I have...
I am using Xcode 11.3. I am trying to copy an address variable from inside a reverse geolocation function to a global variable. However, because the function uses guard statements and nested if's, Xcode wants me to place 'self' infront of my syntax when I try and assign the address. This is fine in that it works, however when the method has finished the global variable is empty and it seems that the address value is only held whilst that method/procedure is executing.
Is there anyway to get the data into a 'global variable' and not to some instance running inside the method? I have added comments at the base of the code where I am trying to give my global variable the contents of the address location (street number, street name and suburb).
My function (method):
// Uses MapKit Delegate
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
//let center = getCenterLocation(for: theMapView)
let center = getCenterLocation(for: theMapView)
let geoCoder = CLGeocoder()
guard let previousLocation = self.previousLocation else { return }
guard center.distance(from: previousLocation) > 100 else { return }
self.previousLocation = center
// The next little bit is mainly error checking stuff
geoCoder.reverseGeocodeLocation(center) { [weak self] (placemarks, error) in
guard let self = self else { return }
if let _ = error {
//TODO: Show alert informing the user
self.myAlertToolbar()
return
}
guard let placemark = placemarks?.first else {
//TODO: Show an alert to the user
self.myAlertToolbar()
return
}
let streetNumber = placemark.subThoroughfare ?? ""
let streetName = placemark.thoroughfare ?? ""
let suburb = placemark.locality ?? ""
if streetName == "" {
DispatchQueue.main.async {
self.addressLabelOutlet.text = "\(suburb)"
}
} else {
DispatchQueue.main.async {
// I want to be able to assign the streetNumber streetName and suburb over to a
// global variable without using self.blahblahblah
self.addressLabelOutlet.text = "\(streetNumber) \(streetName), \(suburb)"
self.myGlobalAddressVariable = String(streetNumber) + streetName + ", " + suburb
print("Address is \(self.myGlobalAddressVariable)")
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire