Swift LocationManager didChangeAuthorizationStatus始终被调用

我有一个实现CLLocationManagerDelegate的视图控制器。 我创建了一个CLLocationManager变量:

 let locationManager = CLLocationManager() 

然后在viewDidLoad ,我设置了属性:

 // Set location manager properties locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters locationManager.distanceFilter = 50 

问题是,即使在我检查授权状态之前,函数也会被调用。

 func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if (status == .AuthorizedWhenInUse) { // User has granted autorization to location, get location locationManager.startUpdatingLocation() } } 

谁能告诉我可能导致这种情况发生的原因?

- locationManager:didChangeAuthorizationStatus:在初始化CLLocationManager后不久调用。

如果需要,您可以在委托方法中请求授权:

 func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .NotDetermined: locationManager.requestAlwaysAuthorization() break case .AuthorizedWhenInUse: locationManager.startUpdatingLocation() break case .AuthorizedAlways: locationManager.startUpdatingLocation() break case .Restricted: // restricted by eg parental controls. User can't enable Location Services break case .Denied: // user denied your app access to Location Services, but can grant access from Settings.app break default: break } } 

请注意,如果您希望这样做,您需要在“及时”的情况下分配代理。

如果您以某种方式延迟委托分配,例如通过异步设置,您可能会错过对- locationManager:didChangeAuthorizationStatus:的初始调用。

斯威夫特3

 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .notDetermined: manager.requestAlwaysAuthorization() break case .authorizedWhenInUse: manager.startUpdatingLocation() break case .authorizedAlways: manager.startUpdatingLocation() break case .restricted: // restricted by eg parental controls. User can't enable Location Services break case .denied: // user denied your app access to Location Services, but can grant access from Settings.app break } }