0
votes

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
What is the error? in order to help you we need some details - Reinier Melian
requestAlwaysAuthorization() displays a dialog to the user, even if they are the fastest user in the world, I don't think they can accept the dialog in the tiny fraction of a second time before startUpdatingLocation() executes in the very next line of code. And what if the user don't grant permission anyway?. There's millions of tutorials and questions about how to implement request authorization, read them, its not as simple as the few lines of code that you have. - Gruntcakes

1 Answers

2
votes

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.