Swift LocationManager didChangeAuthorizationStatus始终被调用

Mik*_*ker 26 cllocationmanager ios swift

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

let locationManager = CLLocationManager()
Run Code Online (Sandbox Code Playgroud)

然后在viewDidLoad,我设置属性:

// Set location manager properties
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 50
Run Code Online (Sandbox Code Playgroud)

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

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

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

Bar*_*che 48

- 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 e.g. 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
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您希望这样做,您需要在"及时"的情况下分配代表.

如果你以某种方式延迟代理分配,例如通过异步设置,你可能会错过初始调用- locationManager:didChangeAuthorizationStatus:.

  • 这对我来说似乎是一个错误,我几乎不把它描述为授权状态的`didChange`.编写对授权状态的实际更改作出反应的代码会受到此行为的影响. (5认同)
  • 万一这对某人也不起作用。在 ios14 中,不再调用此函数,因为它已被弃用。使用: ```func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { if #available(iOS 14.0, *) { switch manager.authorizationStatus {...} } }``` (3认同)
  • 非常感谢你.我没有意识到它在初始化后被调用. (2认同)

Vya*_*lav 6

斯威夫特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 e.g. 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
        }
    }
Run Code Online (Sandbox Code Playgroud)