Location permission check and authorization

2019-06-18 02:15发布

I want my program to display the users location on the map. It was working at first then randomly stopped so i added the code below to try to fix it but I'm having problems. Thanks in advance!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if CLLocationManager.locationServicesEnabled()
        {

            let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
            if status == CLAuthorizationStatus.NotDetermined
            {
                locationManager.requestAlwaysAuthorization()
            }
            } else {

                print("locationServices disenabled")
            }
            locationManager.startUpdatingLocation()
            self.locationManager.startUpdatingLocation()
            self.mapView.showsUserLocation = true
            mapView.delegate = self
            centerMapOnLocation(initialLocation)
            addBoundry()
    }

3条回答
Luminary・发光体
2楼-- · 2019-06-18 02:17

I was having the same issue, even with NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescriptionset in info.plist. My debugger told me to also set NSLocationAlwaysAndWhenInUseUsageDescription...so I did it. It worked!

查看更多
3楼-- · 2019-06-18 02:18

You required to call,

locationManager.requestAlwaysAuthorization() 

as well

 locationManager.requestWhenInUseAuthorization()

to use location smoothly in foreground also!!!

and you should not need two instance to call startupdatinglocation. keep one. you should use instance or global variable instead of local to get location throughout the scope.

Update :

You have to set two keys in info.plist like, NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription with it's usage description.

查看更多
不美不萌又怎样
4楼-- · 2019-06-18 02:20

If you want the "WhenInUse" notification you should only add "Privacy - Location When In Use Usage Description" in your info.plist but if you want the "Always" access your info.plist should look like this info.plist screenshot:

Image

You don't have to add any request authorization like requestAlwaysAuthorization or requestWhenInUseAuthorization

查看更多
登录 后发表回答