Background
I'm trying to build a class that will easily convert string like addresses into a CLLocationCoordinate2D for later use that will be saved to a database.
I have a class that is similar to below:
final class PublishMapData: ObservableObject {
@Published var userAddressLat: Double = 0.0
@Published var userAddressLong: Double = 0.0
func saveMapData(address: String){
let address = "One Apple Park Way, Cupertino, CA 95014" //simulating the call from a save button for instance
convertAddress(address: address)
print(String(userAddressLat)) //this prints 0.0
print(String(userAddressLong)) //this print 0.0
//{...extra code here...}
//this is where I would be storing the coordinates into something like Firestore for later use
}
func convertAddress(address: String) {
getCoordinate(addressString: address) { (location, error) in
if error != nil {
return
}
DispatchQueue.main.async {
self.userAddressLat = location.latitude
print(self.userAddressLat) //this prints the correct value
self.userAddressLong = location.longitude
print(self.userAddressLong) //this prints the correct value
}
}
}
private func getCoordinate(addressString : String, completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
completionHandler(location.coordinate, nil)
return
}
}
completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
}
}
}
For some reason, I'm not getting the lat, long values from the convertAddress function to properly get stored within the @Published variables. What am I doing wrong? I'm still learning Swift. Thanks in advance for any assistance.