Swift - 如何等到 GPS returns 坐标正确

Swift - How to wait until GPS returns correct coordinates

我目前正在 运行 解决当我第一次 运行 调用该位置时 GPS 返回坐标 0,0 的问题。如果我稍后再次调用相同的函数,它 returns 正确的值,所以我想我只需要等待检索坐标,直到 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()
         }
    }

从某种意义上说,您是对的,您需要等待 GPS“预热”——但是,这将在未来不确定的时间发生。

您在 LocationManager 中遗漏了相当多的代码,但大概您有更新 @Published 属性 location 的委托方法。

您可能应该在 location 上监听变化,然后在必要时调用 reload()(即第一次调用)。

可能看起来有点像


struct ContentView: View {

    @ObservedObject private var locationManager = LocationManager()
    @State private var hasLoaded = false
    
    var body: some View {
         VStack {
            Text("Hello, world")
         }.onReceive(locationManager.$location) { newLocation in
            if let newLocation = newLocation {
                reload(location: newLocation.coordinate)
            }
         }
    }
    
    func reload(location: CLLocationCoordinate2D) {
        guard hasLoaded == false else {
            return
        }
        hasLoaded = true
        //http request here
    }
}