Implement CLLocationManagerDelegate methods in Swift

user1327904 picture user1327904 · Jun 5, 2014 · Viewed 42.1k times · Source

I've been trying to get this to work for awhile now, and I've come here to ask- how do I go about with using the CLLocationManagerDelegate methods in Swift? I've put this at the top of my class:

var locationManager = CLLocationManager()

I've put the following into my viewDidLoad method:

locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()

And I've tried using these delegate methods with no avail:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
    locationReceived = true
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationReceived = false
}

I've also tried using @optional in front of the functions, but Xcode then throws a compiler error. Any ideas?

Answer

Wesley Smith picture Wesley Smith · Jun 5, 2014

You need to add the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key to your plist if you haven't already, they are now mandatory,


iOS8+ requires one of these two strings to be set to use locations. Which one you use depends on how you intend ask for the location.

  • Use NSLocationAlwaysUsageDescription for apps that want to use the device's location even when the app is not open and being used.

  • Use NSLocationWhenInUseUsageDescription for apps that want to use the device's location only when the app is open and in use.

Note: When you add the strings, before you build and run, delete the app off your device and let it do a fresh install. It seems that if the app was authorized to use locations before you upgraded to iOS8 it doesn’t ask for your permission again and doesn’t see that you set those strings. Doing a delete and clean install solves this.

Setting either of the strings prompts a pop up on install/first use along the lines of: "Allow "ThisApp" to access your location even when you are not using the App"

Here's a Screenshot of the plist file.

enter image description here