iOS Guides | Samples

CoreLocation.CLLocationManager Class

Manages the delivery of location, region, and heading events to your application.

See Also: CLLocationManager

Syntax

[Foundation.Register("CLLocationManager", true)]
public class CLLocationManager : NSObject

Remarks

Requesting Authorization

Starting with iOS 8, developers that want to request access to the location information must request permission from the user to do so before they can receive events. This is done by calling either the CLLocationManager.RequestWhenInUseAuthorization or the CLLocationManager.RequestAlwaysAuthorization methods. When these methods are invoked, the system will prompt the user for authorization, and if he grants it, the CLLocationManager.AuthorizationChanged event will be raised if set (or if you are using the Delegate idiom, the CLLocationManagerDelegate.AuthorizationChanged method will be invoked.

Additionally, developers must add one or both of the keys NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription in their app's info.plist. These keys are strings that can be used to describe why the app needs location access.

Developers should use an idiom like this:

c# Example

var manager = new CLLocationManager();
manager.AuthorizationChanged += (sender, args) => {
	Console.WriteLine ("Authorization changed to: {0}", args.Status);
};
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0))
    manager.RequestWhenInUseAuthorization();

Tracking the device's location

The most common use-case for the CLLocationManager is tracking the device while the application is in the foreground. (See also "Background Updating and Deferred Mode" below.)

Application developers may use either C#-style events or Apple's delegate-object pattern to track foreground location updating. For C#-style events, developers can use the CLLocationManager.LocationsUpdated event:

C# Example

var mgr = new CLLocationManager();
mgr.LocationsUpdated += (sender, e) => {
	foreach(var loc in e.Locations)
	{
		Console.WriteLine(loc);
	}
};
mgr.StartUpdatingLocation();

F# Example

let mgr = new CLLocationManager()
mgr.LocationsUpdated.Add( fun e ->
    e.Locations |> Seq.map Console.WriteLine |> ignore )
mgr.StartUpdatingLocations()

While C#-style events are more concise, the CLLocationManager must use the delegate-object pattern for certain behaviors (for instance, deferred updating), and it may be more consistent for an application to use the delegate-object pattern even when C#-style events are available. The delegate-object pattern consists of assigning a customized CLLocationManagerDelegate object to the CLLocationManager.Delegate property of the CLLocationManager:

C# Example

var mgr = new CLLocationManager();
mgr.Delegate = new MyLocationDelegate();
mgr.StartUpdatingLocation();
//...etc...

public class MyLocationDelegate : CLLocationManagerDelegate {
	public override void LocationsUpdated (CLLocationManager manager, CLLocation[] locations) {
		foreach(var loc in locations) {
			Console.WriteLine(loc);
		}
	}
}

F# Example

let mgr = new CLLocationManager()
mgr.Delegate <- new MyLocationDelegate()
mgr.StartUpdatingLocation()
//...etc...

type MyLocationDelegate () = inherit CLLocationManagerDelegate()
    override this.LocationsUpdated ( manager : CLLocationManager, locations : CLLocation[] ) = 
        locations 
        |> Seq.map Console.WriteLine
        |> ignore

Region monitoring (Geofencing)

The CLLocationManager can track the device's entry and exit from geographical regions (geofences). A region will be a subtype of CLRegion : either a CLCircularRegion or a region associated with an iBeacon, of type CLBeaconRegion.

CLRegion identity should only be compared via the CLRegion.Identifier property. Regions are monitored at the operating-system level and new CLRegion objects with the specified CLRegion.Identifier may be instantiated by the system when the device enters or exists an area; these CLRegions will be different objects (myExpectedRegion != myReceivedRegion) but will have the same CLRegion.Identifier (myExpectedRegion.Identifier.Equals(myReceivedRegion.Identifier, StringComparison.Ordinal)).

Application developers can use either C#-style events or Apple's delegate-object pattern:

C# Example

var rgn = new CLCircularRegion(new CLLocationCoordinate2D(latitude, longitude), 50, "target");
mgr = new CLLocationManager();
mgr.RegionEntered += (s,e) => Console.WriteLine("Entered region " + e.Region.Identifier);
mgr.RegionLeft += (s,e) => Console.WriteLine("Left region " + e.Region.Identifier);
mgr.StartMonitoring(rgn);

F# Example

let rgn = new CLCircularRegion(new CLLocationCoordinate2D(latitude, longitude), 50, "target")     
let mgr = new CLLocationManager()
mgr.RegionEntered.Add( fun e -> Console.WriteLine("Entered region " + e.Region.Identifier))
mgr.RegionLeft.Add( fun e -> Console.WriteLine("Left region " + e.Region.Identifier))
mgr.StartMonitoring(rgn)

C# Example

var rgn = new CLCircularRegion(new CLLocationCoordinate2D(latitude, longitude), 50, "target");
mgr = new CLLocationManager();
var del = new MyLocationDelegate();
mgr.Delegate = del;
mgr.StartMonitoring(rgn);
//...etc...

public class MyLocationDelegate : CLLocationManagerDelegate {
    public override void RegionEntered (CLLocationManager mgr, CLRegion rgn) {
        Console.WriteLine ("Entered region " + rgn.Identifier);
    }

    public override void RegionLeft (CLLocationManager mgr, CLRegion rgn) {
        Console.WriteLine ("Left region " + rgn.Identifier);
    }
}

F# Example

let rgn = new CLCircularRegion(new CLLocationCoordinate2D(latitude, longitude), 50, "target")
let mgr = new CLLocationManager()
mgr.Delegate <- new MyLocationDelegate()
mgr.StartMonitoring(rgn)
//...etc...

type MyLocationDelegate () = inherit CLLocationManagerDelegate()
    override this.RegionEntered ( mgr : CLLocationManager, rgn : CLRegion ) = 
        Console.WriteLine ("Entered region " + rgn.Identifier)

    override this.RegionLeft ( mgr : CLLocationManager, rgn : CLRegion ) =
        Console.WriteLine ("Left region " + rgn.Identifier)

iBeacon Ranging

In iOS 7, Apple introduced iBeacons, which combine region-processing using server and GPS services and nearby promixity ranging using Bluetooth Low-Energy (BLE) signaling.

Once within a CLBeaconRegion (see previous section), applications may track "ranging" events relating to fine-grained changes in the distance between the device and nearby iBeacons. iBeacon ranging is primarily a function of radio signal strength, which can vary significantly based on environment, electrical noise, etc. Application developers should not attempt to estimate precise distances from the CLBeacon.Proximity or CLBeacon.RSSI properties.

Ranging is done with code similar to:

iBeacons also support "ranging" for determining physical proximity with a higher precision with the CLBeacon.Proximity property. The following example shows how ranging should be used as a qualitative measure:

C# Example

locationManager.DidRangeBeacons += (lm, rangeEvents) => {
    switch(rangeEvents.Beacons[0].Proximity){
    case CLProximity.Far : 
        Console.WriteLine("You're getting colder!");
        break;
    case CLProximity.Near :
        Console.WriteLine("You're getting warmer!");
        break;
    case CLProximity.Immediate :
        Console.WriteLine("You're red hot!");
        break;

F# Example

locationManager.DidRangeBeacons.Add(fun rangeEvents ->
    let s = match rangeEvents.Beacons.[0].Proximity with
        | CLProximity.Far  -> "You're getting colder!"
        | CLProximity.Near -> "You're getting warmer!"
        | CLProximity.Immediate -> "You're red hot!"
        | CLProximity.Unknown -> "I can't tell"
        | _ -> raise(ArgumentOutOfRangeException("Unknown argument"))
    Console.WriteLine(s)   
)
locationManager.StartRangingBeacons(beaconRegion)
Operation

Background Updating and Deferred Mode

Locations can be updated while the application is in the background. This requires that the info.plist be modified using either Xamarin Studio's visual editor:

Or by adding the key manually:

C# Example

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

Power consumption is an important consideration for all backgrounding scenarios. In the case of location data, GPS-enabled hardware may be able to record and cache accurate location but defer the delivery to the application for some amount of time. This "deferred mode" has several constraints:

If those conditions are satisfied, the application can request deferred delivery when backgrounded by calling the CLLocationManager.AllowDeferredLocationUpdatesUntil method.

Operation

Importance of Delegate object

Generally, when using Xamarin.iOS, developers can freely choose whether to use C# events or Apple-style "delegate objects" to react to object lifecycle events. Several CLLocationManager methods, however, require the delegate-object pattern. For instance, CLLocationManager.AllowDeferredLocationUpdatesUntil will raise a runtime exception if the CLLocationManager.Delegate property is not set to an object whose class implements CLLocationManagerDelegate.LocationsUpdated method.

Related content

Requirements

Namespace: CoreLocation
Assembly: Xamarin.iOS (in Xamarin.iOS.dll)
Assembly Versions: 0.0.0.0

The members of CoreLocation.CLLocationManager are listed below.

See Also: NSObject

Public Constructors

Default constructor that initializes a new instance of this class with no parameters.

Protected Constructors

Constructor to call on derived classes to skip initialization and merely allocate the object.
A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

Public Properties

ActivityTypeCLActivityType. Used to provide the operating system clues for better power consumption / accuracy.
AllowsBackgroundLocationUpdatesBoolean. Gets or sets a Boolean value that controls whether the application will respond to location updates while it is suspended.
[read-only]
override
ClassHandleIntPtr. The handle for this class.
[read-only]
static
DeferredLocationUpdatesAvailableBoolean. Whether background-generated deferred location data are available.
DelegateICLLocationManagerDelegate. An instance of the CoreLocation.ICLLocationManagerDelegate model class which acts as the class delegate.
DesiredAccuracyDouble. The accuracy preferred by the app. (Coarser accuracies consume less power.)
DistanceFilterDouble. The minimum horizontal distance, in meters, the device has to move before issuing a location update.
[read-only]
HeadingCLHeading. The most recent heading (direction in which the device is traveling).
[read-only]
static
HeadingAvailableBoolean. Whether the CLLocationManager.Heading property is not null.
HeadingFilterDouble. The minimum change in heading, in degreees, necessary to generate a location update.
HeadingOrientationCLDeviceOrientation. The orientation used to determine heading calculations.
[read-only]
static
IsRangingAvailableBoolean. Gets a Boolean value that tells whether the device can range Bluetooth beacons.
[read-only]
LocationCLLocation. The most recently-retrieved CLLocation.
[read-only]
static
LocationServicesEnabledBoolean. Whether location services are available.
[read-only]
MaximumRegionMonitoringDistanceDouble. The largest boundary distance, in meters, that can be assigned to a region.
[read-only]
static
MaxTimeIntervalDouble. Represents the value associated with the constant CLTimeInternalMax
[read-only]
MonitoredRegionsNSSet. The set of CLRegions being monitored by the app.
PausesLocationUpdatesAutomaticallyBoolean. Whether the system is allowed to pause location updates (for instance, if the device has not moved in awhile).
PurposeString. Developers should not use this deprecated property.
[read-only]
RangedRegionsNSSet. The set of CLRegions being tracked using ranging.
[read-only]
static
RegionMonitoringAvailableBoolean. Application developers should use CLLocationManager.IsMonitoringAvailable rather than this deprecated method.
[read-only]
static
RegionMonitoringEnabledBoolean. Application developers should use CLLocationManager.IsMonitoringAvailable rather than this deprecated method.
ShouldDisplayHeadingCalibrationCLLocationManagerEventArgs. Delegate invoked by the object to get a value.
ShowsBackgroundLocationIndicatorBoolean.
[read-only]
static
SignificantLocationChangeMonitoringAvailableBoolean. Whether "significant location change" monitoring (e.g., via cell tower switch) is available.
[read-only]
static
StatusCLAuthorizationStatus. The authorization status of the app (e.g., if the app is denied access to location services).
WeakDelegateNSObject. An object that can respond to the delegate protocol for this type

Public Methods

AllowDeferredLocationUpdatesUntil(Double, Double)
Suggests that location updates are deferred until either distance has been traveled or timeout has passed.
DisallowDeferredLocationUpdates()
Turns off deferred background location updates.
DismissHeadingCalibrationDisplay()
Removes the heading calibration view from the display.
static
IsMonitoringAvailable(Class) : Boolean
Determines whether the device supports region monitoring for the specified kind of CLRegion.
static
IsMonitoringAvailable(Type) : Boolean
Determines whether the device supports region monitoring for the specified kind of CLRegion.
RequestAlwaysAuthorization()
Displays an interface to the user that requests authorization to use location services any time that the app is running.
RequestLocation()
Requests the current location.
RequestState(CLRegion)
Asynchronously requests information on the state of the region.
RequestWhenInUseAuthorization()
Displays an interface to the user that requests authorization to use location services any time that the app is in the foreground.
StartMonitoring(CLRegion)
Begins monitoring region for entry and exit.
StartMonitoring(CLRegion, Double)
Starts monitoring the region.
StartMonitoringSignificantLocationChanges()
Starts monitoring for significant changes.
StartMonitoringVisits()
Starts generating events in response to visits.
StartRangingBeacons(CLBeaconRegion)
Starts delivering notifications about beacons in region.
StartUpdatingHeading()
Starts updating the heading.
StartUpdatingLocation()
Starts updating the location
StopMonitoring(CLRegion)
Stops monitoring the region.
StopMonitoringSignificantLocationChanges()
Starts monitoring significant location changes.
StopMonitoringVisits()
Stops generating events in response to visits.
StopRangingBeacons(CLBeaconRegion)
Stops tracking beacons in the region.
StopUpdatingHeading()
Stops updating the heading.
StopUpdatingLocation()
Stops updating the location.

Protected Methods

override
Dispose(Boolean)
Releases the resources used by the CLLocationManager object.

Public Events

AuthorizationChangedEvent raised by the object.
DeferredUpdatesFinishedEvent raised by the object.
DidDetermineStateEvent raised by the object.
DidRangeBeaconsEvent raised by the object.
DidStartMonitoringForRegionEvent raised by the object.
DidVisitEvent raised by the object.
FailedEvent raised by the object.
LocationsUpdatedEvent raised by the object.
LocationUpdatesPausedEvent raised by the object.
LocationUpdatesResumedEvent raised by the object.
MonitoringFailedEvent raised by the object.
RangingBeaconsDidFailForRegionEvent raised by the object.
RegionEnteredEvent raised by the object.
RegionLeftEvent raised by the object.
UpdatedHeadingEvent raised by the object.
UpdatedLocationEvent raised by the object.