CLLocationManager authorization issue iOS 8

brisi123 picture brisi123 · Jul 10, 2014 · Viewed 25.9k times · Source

I am working on a piece of Swift code for iOS 8. I am trying to do something which involves location, and so i have implemented the following in my swift view controller file:

let locationManger:CLLocationManager = CLLocationManager()

var speedReceived:Double = 0

override func viewDidLoad() {
    super.viewDidLoad()
    locationManger.delegate = self
    locationManger.desiredAccuracy = kCLLocationAccuracyBest
    let authstate = CLLocationManager.authorizationStatus()
    if(authstate == CLAuthorizationStatus.NotDetermined){
       println("Not Authorised")  
      locationManger.requestWhenInUseAuthorization()
    }
    // Do any additional setup after loading the view, typically from a nib.
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
    var location:CLLocation = locations[locations.count - 1] as CLLocation
    if(location.horizontalAccuracy > 0){
        self.speedReceived = location.speed
        println(self.speedReceived)
    }
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
   println("Couldn't get your location")
}

However, I can't seem to get this code to work. It doesn't save my preference for location use. it doesn't even prompt me to give permit to access location. I have tried updating my info.plist. But it's not working. Btw, if i select always in the privacy settings within the simulator, it works if i switch back to the app immediately. can anyone help? I am sure that that's the problem because i get Not Authorised on my console.

Any help?

Answer

Alex Peda picture Alex Peda · Jul 10, 2014

It's an iOS 8 related issue. You have to put NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys in your .plist file (value may be an additional message that will be presented in location alert). These keys are required in iOS 8.

How it's said in Apple guidelines:

This key is required when you use the requestAlwaysAuthorization method of the CLLocationManager class to request authorization for location services. If this key is not present and you call the requestAlwaysAuthorization method, the system ignores your request and prevents your app from using location services.