Swift LocationManager didChangeAuthorizationStatus Always Called

北城以北 提交于 2019-12-03 14:41:19

问题


I have a view controller which implements the CLLocationManagerDelegate. I create a the CLLocationManager variable:

let locationManager = CLLocationManager()

Then in the viewDidLoad, I set properties:

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

The problem comes that the function gets called even before I check the authorization status.

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

Can anyone inform me what could be causing this to occur?


回答1:


- locationManager:didChangeAuthorizationStatus: is called shortly after the CLLocationManager is initialised.

You can request authorization inside the delegate method if you want:

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
    }
}

Be aware that you need to assign the delegate in a 'timely' matter if you want this to work.

If you would somehow delay the delegate assignment, e.g. by setting it asynchronously, you might miss the initial call to - locationManager:didChangeAuthorizationStatus:.




回答2:


Swift 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
        }
    }


来源:https://stackoverflow.com/questions/30106341/swift-locationmanager-didchangeauthorizationstatus-always-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!