如何正确获取用户坐标?

How to properly get user coordinates?

MapViewController采用这种CLLocationManagerDelegate协议:

extension MapViewController:CLLocationManagerDelegate{

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let usrLocation:CLLocation = locations[0] as CLLocation

        // readable
        print("lat = \(usrLocation.coordinate.latitude)")
        print("lon = \(usrLocation.coordinate.longitude)")

        self.userLocation = usrLocation

        locationManager.stopUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Error \(error)")
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        switch status {
        case .restricted, .denied, .notDetermined:

            // no issue here because I make a very generic request to a server
            // AND I don't need user coordinates

            break

        case .authorizedWhenInUse, .authorizedAlways:

            // here I need user coordinates because I need to request content to a server
            // based on user coordinates but when I check for userLocation
            // at first I find <+0.00000000,+0.00000000> +/- 0.00m (speed -1.00 mps / course -1.00

            print("----------------")
            print(userLocation)
            print("----------------")

            break
        }
    }

我需要 .authorizedWhenInUse/.autorizeAlways 案例正文中的用户位置数据,因为我需要发送电流 用户坐标到服务器。问题是当我需要它们时,我首先 得到一个像这样的用户位置:

 <+0.00000000,+0.00000000> +/- 0.00m (speed -1.00 mps / course -1.00>

userLocationviewcontroller class 的成员,其值设置在 locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 中。我应该将请求移至此功能吗?以及如何检查该上下文中的用户状态?我只想请求授权该应用程序的用户检索他们的位置。我希望解决方案不是计时器和多次检查,但任何帮助表示赞赏:-)

仅仅因为您收到了 .authorizedWhenInUse.authorizedAlways 并不意味着您已经开始定位服务。这只是意味着它已被授权。您不应该尝试检索 didChangeAuthorization 中的用户位置。

因此,您应该调用 startUpdatingLocation and move your code that sends this location to the server to your didUpdateLocations 方法。