所以我想用swiftui做一个iOS应用,对一个地址进行前向地理编码,然后把这些坐标放在变量中,以便在我的其他视图中使用。我用于向前地理编码的函数是这样的。
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()
}
}
我的问题是,我应该如何在我的contentview文件中调用这个函数,这样我就可以把坐标保存为变量,我如何调用这个函数把它们打印到屏幕上,以验证代码是否正确运行。
你可以像这样在 onAppear()
方法,以一种非常简单的方式。但是,我鼓励你使用视图模型来使用地址获取坐标。
struct ContentView: View {
@State var myText = "Some Text just for reference"
@State var location: CLLocationCoordinate2D?
var body: some View {
Text(myText)
.onAppear {
self.getLocation(from: "Some Address") { coordinates in
print(coordinates) // Print here
self.location = coordinates // Assign to a local variable for further processing
}
}
}
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)
}
}
}