Getting error about asking for location permission

时间:2016-07-11 19:00:38

标签: ios swift permissions location mapkit

Getting an error about asking for location permission: "Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first." The problem is I already did and it was working fine earlier until I added a url scheme for something completely different.

This is in my ViewController:

override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true
        //your loc
        mapView.delegate = self
        let initialLocation = CLLocation(latitude: 39, longitude: 77)
        centerMapOnLocation(initialLocation)
        }

1 个答案:

答案 0 :(得分:2)

You need to ask if user already has granted permission to track their location:

if CLLocationManager.authorizationStatus() == .NotDetermined {
    manager.requestAlwaysAuthorization()
}

Then you need a callback function that will be called when the permission is granted:

func locationManager(manager: CLLocationManager,
                     didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
    if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
        manager.startUpdatingLocation()
        // ...
    }
}

Remember you have to do this asynchronously, because you know when to ask for permissions (when a view controller did load, for example), but you do not know when the user will click the allow button.

And do not forget to set the NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription, otherwise it will not prompt.