【发布时间】:2021-04-28 23:35:05
【问题描述】:
当我第一次运行它时调用位置时,我目前遇到 GPS 返回坐标 0,0 的问题。如果我在一秒钟后再次调用相同的函数,它会返回正确的值,所以我想我只需要等待检索坐标,直到 GPS “预热”,但我不知道该怎么做。
这是我正在调用的函数:
func reload(){
var coor = self.locationManager.location != nil ?
self.locationManager.location!.coordinate :
CLLocationCoordinate2D()
//I send a http request using the gps data here
...
}
}
我在 .onapear 上为视图调用此函数,它在调试时检索正确的数据,但在独立运行时不检索。我用视图的其他@state 变量初始化位置管理器。
位置经理:
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate
{
@Published var location: CLLocation? = nil
@Published var locationAllowed:Bool = true
private let locationManager = CLLocationManager()
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
...
}
这是程序的一般结构:
struct ContentView: View {
@ObservedObject private var locationManager = LocationManager()
var body: some View {
View{
}.onAppear(){
Reload()
}
}
【问题讨论】:
标签: swift swiftui core-location