Wednesday, October 15, 2014

Getting Permission to Access User Location in iOS8 with Xamarin iOS

If you’ve been developing location aware applications for iOS for a while you know that you could simply attempt to access location data in your code.  And the first time your app was run on a device, it would ask the user for permission, hopefully they say yes, and things are easy.

There are a few additional steps now in iOS 8.

The first thing you need to do is add one or two keys to your applications info.plist.  You can do this by hand with a text editor or click on the info.plist files and use the “Source” view from within Xamarin Studio.

If you’re just using location data in a normal application, the key is:

NSLocationWhenInUseUsageDescription which is a string type.  The string value is the message that will be displayed to the user the first time your application attempts to receive location data. 

Alternatively, if you’re application is background enabled for location data, you would use:

NSLocationAlwaysUsageDescription which again has a string value.

The idea with these keys, is that you can now describe to your users why you require location information.  Alternatively, you can leave the values blank to show a generic popup message.

The new keys in your info.plist would look like this:

<key>NSLocationWhenInUseUsageDescription</key>
<string>In order to track your running routes</string>

or for a background enabled app without a custom message:

<key>NSLocationAlwaysUsageDescription</key>
<string></string>

 

infop

 

Additionally, in your code you now need to specifically request authorization by calling a method defined on an instance of the LocationManager class.  RequestWhenInUseAuthorization () for standard applications and RequestAlwaysAuthorization () for background enabled apps.

 

1 if (CLLocationManager.LocationServicesEnabled)
2 {
3 LocMgr = new CLLocationManager();
4
5 ...
6
7 // request permission
8 LocMgr.RequestWhenInUseAuthorization ();
9 // Start location updates
10 LocMgr.StartUpdatingLocation ();
11
12 ...
13 }

permission