Showing posts with label requestAlwaysAuthorization. Show all posts
Showing posts with label requestAlwaysAuthorization. Show all posts

Monday, September 29, 2014

Swift - Checking if a method exists

A lot of changes has happened in iOS 8, and a lot of APIs require that you call certain new methods before they can work. Examples are locations, notifications, and more.

To ensure that your app can work on older versions of iOS as well as the new iOS 8, it is important that you only call the new API when your app is running on iOS 8. The best way is to test if a method exists. You can do so via the respondsToSelector() method. The following example tests to see if the UIApplication object contains the registerUserNotificationSettings() method:

if application.respondsToSelector("registerUserNotificationSettings") {

}

Another example:

if self.locationManager.respondsToSelector("requestAlwaysAuthorization") {


}

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.