【发布时间】:2020-04-23 00:55:02
【问题描述】:
所以我正在尝试使用 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 文件中调用此函数,以便将坐标保存为变量,以及如何调用该函数将它们打印到屏幕上,以验证代码是否正常运行。
【问题讨论】:
标签: ios swiftui core-location