So I'm trying to make an iOS app using swiftui that forward geocodes an address and then places those coordinates in variables that can be used in the rest of my views. The function I'm using for forward geocoding looks like this:
import SwiftUI
import CoreLocation
struct ContentView: View {
@State var myText = "Some Text just for reference"
@State var location: CLLocationCoordinate2D?
@State var lat: Double?
@State var long: Double?
var body: some View {
VStack{
Text(myText)
.onAppear {
self.getLocation(from: "22 Sunset Ave, East Quogue, NY") { coordinates in
print(coordinates ?? 0) // Print here
self.location = coordinates // Assign to a local variable for further processing
self.long = coordinates?.longitude
self.lat = coordinates?.latitude
}
}
Text("\(long)")
Text("\(lat)")
}
}
func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location?.coordinate else {
completion(nil)
return
}
completion(location)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
My questions are, how should I be calling this function inside of my contentview file so I can save the coordinates as variables and how do I call the function to print them to the screen just to verify the code is operating correctly.