我以这种方式使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>
userLocation
是viewcontroller
类的成员,其值在locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
中设置。我应该将请求移至该功能吗?在该情况下,如何检查用户状态?我只想向授权应用程序以检索其位置的用户发出请求。我希望解决方案不是一个计时器和多个检查,但可以提供任何帮助:-)
答案 0 :(得分:3)
仅仅是因为您收到了.authorizedWhenInUse
或.authorizedAlways
,并不意味着您已经开始定位服务。这仅表示它已被授权。您不应该尝试在didChangeAuthorization
中检索用户位置。
因此,您应该调用startUpdatingLocation
并将将此位置发送到服务器的代码移动到didUpdateLocations
方法。