【问题标题】:Swift - How to wait until GPS returns correct coordinatesSwift - 如何等到 GPS 返回正确的坐标
【发布时间】: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


    【解决方案1】:

    从某种意义上说,您是对的,您需要等待 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多