Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapKit in iOS 8 and Swift

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?

like image 714
Phil Avatar asked Jun 08 '14 11:06

Phil


3 Answers

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.

like image 78
Robert Mcc Avatar answered Jan 26 '23 01:01

Robert Mcc


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).

like image 23
David Mendels Avatar answered Jan 26 '23 00:01

David Mendels


It is NSLocationWhenInUseUsageDescription, not NSLocationWhenInUsageDescription. Most places online have the wrong key

like image 44
Jonathan Brown Avatar answered Jan 26 '23 00:01

Jonathan Brown