I'm trying to use MapKit on iOS 8 and I keep getting the error:
Trying to start MapKit location updates without prompting for location authorization. Must call
-[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager
requestAlwaysAuthorization] first.
Looking it up here, I found that I had to implement NSLocationWhenInUsageDescription
in my plist and also make a call to locationManager.requestWhenInUseAuthorization()
but nothing happens and I still get that error in the console. What am I doing wrong?
In my application delegate I made an optional var for the locationManager outside the class and then set
locManager = CLLocationManager()
locManager!.requestWhenInUseAuthorization()
This causes the alert view to pop up with your NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription if you change it appropriately.
Then in the view controller file I made another var outside the class to hold a local CLLocationManager. I then set
if locManager {
locMan = locManager!
locMan!.delegate = self
}
Then you can use the delegate method
func locationManager(_manager: CLLocationManager!,didChangeAuthorizationStatus status: CLAuthorizationStatus)
which gets called when the authorisation status changes, which it does when the user responds to the pop up. Inside this you can use this bit of code to put the user location on the map
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
map.showsUserLocation = true
}
will add the users location to the map only if you are authorised for when in use.
I have been bothered by that one as well, until I realized that the info.plist
key has changed. If you had NSLocationUsageDescription
in, you will need to change to either NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
(set at least one to YES
), it is now mandatory in iOS8.
And then, Robert's code works, as it should (thanks for sharing).
It is NSLocationWhenInUseUsageDescription, not NSLocationWhenInUsageDescription. Most places online have the wrong key
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With