Thursday, September 25, 2014

iOS 8 - Getting Location Data

Getting location data in iOS 8 has changed drastically. Here is what you need to do if you are using the CLLocationManager class to get a location in iOS 8.

In iOS 8, you need to add the following two keys in your info.plist file:

For getting location in the foreground

Key
NSLocationWhenInUseUsageDescription

Value
"This app will display your current location" (up to you to write anything you want here)

For getting location in the background

Key
NSLocationAlwaysUsageDescription

Value
"This app will log your location into a database" (up to you to write anything you want here)

Before you use the startUpdatingLocation() method, you have to request for user's permission. To use the location in the foreground, call the requestWhenInUseAuthorization() method:

var lm: CLLocationManager!
...
        if (UIDevice.currentDevice().systemVersion as NSString).floatValue>=8.0 {            
            //---request for foreground location use---
            lm.requestWhenInUseAuthorization()
        }
        
        lm.startUpdatingLocation()


If you want to continue getting location data in the background, call the requestAlwaysAuthorization() method:

        if (UIDevice.currentDevice().systemVersion as NSString).floatValue>=8.0 {
            //---request for background location use---
            lm.requestAlwaysAuthorization()
        }


Note that if you want the app to access location information both in the foreground and in the background, it is sufficient to call the requestAlwaysAuthorization() method.

No comments: