CLLocationManager Class

Definition

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

[Foundation.Register("CLLocationManager", true)]
public class CLLocationManager : Foundation.NSObject
type CLLocationManager = class
    inherit NSObject
Inheritance
CLLocationManager
Attributes

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 RequestWhenInUseAuthorization() or the RequestAlwaysAuthorization() methods. When these methods are invoked, the system will prompt the user for authorization, and if he grants it, the AuthorizationChanged event will be raised if set (or if you are using the Delegate idiom, the AuthorizationChanged(CLLocationManager, CLAuthorizationStatus) 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:


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 LocationsUpdated event:


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

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 Delegate property of the CLLocationManager:


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); } } }


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 Identifier property. Regions are monitored at the operating-system level and new CLRegion objects with the specified 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 Identifier (myExpectedRegion.Identifier.Equals(myReceivedRegion.Identifier, StringComparison.Ordinal)).

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


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);

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)

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);
}

}


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 Proximity or P:CoreLocation.CLBeacon.RSSI properties.

Ranging is done with code similar to:

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


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;

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)       

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:


<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 AllowDeferredLocationUpdatesUntil(Double, Double) method.

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, AllowDeferredLocationUpdatesUntil(Double, Double) will raise a runtime exception if the Delegate property is not set to an object whose class implements LocationsUpdated(CLLocationManager, CLLocation[]) method.

Constructors

CLLocationManager()

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

CLLocationManager(IntPtr)

A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

CLLocationManager(NSObjectFlag)

Constructor to call on derived classes to skip initialization and merely allocate the object.

Properties

ActivityType

Used to provide the operating system clues for better power consumption / accuracy.

AllowsBackgroundLocationUpdates

Gets or sets a Boolean value that controls whether the application will respond to location updates while it is suspended.

Class (Inherited from NSObject)
ClassHandle

The handle for this class.

DebugDescription

A developer-meaningful description of this object.

(Inherited from NSObject)
DeferredLocationUpdatesAvailable

Whether background-generated deferred location data are available.

Delegate

An instance of the CoreLocation.ICLLocationManagerDelegate model class which acts as the class delegate.

Description

Description of the object, the Objective-C version of ToString.

(Inherited from NSObject)
DesiredAccuracy

The accuracy preferred by the app. (Coarser accuracies consume less power.)

DistanceFilter

The minimum horizontal distance, in meters, the device has to move before issuing a location update.

Handle

Handle (pointer) to the unmanaged object representation.

(Inherited from NSObject)
Heading

The most recent heading (direction in which the device is traveling).

HeadingAvailable

Whether the Heading property is not null.

HeadingFilter

The minimum change in heading, in degreees, necessary to generate a location update.

HeadingOrientation

The orientation used to determine heading calculations.

IsDirectBinding (Inherited from NSObject)
IsProxy (Inherited from NSObject)
IsRangingAvailable

Gets a Boolean value that tells whether the device can range Bluetooth beacons.

Location

The most recently-retrieved CLLocation.

LocationServicesEnabled

Whether location services are available.

MaximumRegionMonitoringDistance

The largest boundary distance, in meters, that can be assigned to a region.

MaxTimeInterval

Represents the value associated with the constant CLTimeInternalMax

MonitoredRegions

The set of CLRegions being monitored by the app.

PausesLocationUpdatesAutomatically

Whether the system is allowed to pause location updates (for instance, if the device has not moved in awhile).

Purpose

Developers should not use this deprecated property.

RangedRegions

The set of CLRegions being tracked using ranging.

RegionMonitoringAvailable

Application developers should use IsMonitoringAvailable(Type) rather than this deprecated method.

RegionMonitoringEnabled

Application developers should use IsMonitoringAvailable(Type) rather than this deprecated method.

RetainCount

Returns the current Objective-C retain count for the object.

(Inherited from NSObject)
Self (Inherited from NSObject)
ShouldDisplayHeadingCalibration

Delegate invoked by the object to get a value.

ShowsBackgroundLocationIndicator
SignificantLocationChangeMonitoringAvailable

Whether "significant location change" monitoring (e.g., via cell tower switch) is available.

Status

The authorization status of the app (e.g., if the app is denied access to location services).

Superclass (Inherited from NSObject)
SuperHandle

Handle used to represent the methods in the base class for this NSObject.

(Inherited from NSObject)
WeakDelegate

An object that can respond to the delegate protocol for this type

Zone (Inherited from NSObject)

Methods

AddObserver(NSObject, NSString, NSKeyValueObservingOptions, IntPtr)

Registers an object for being observed externally (using NSString keyPath).   Observed changes are dispatched to the observer’s object ObserveValue(NSString, NSObject, NSDictionary, IntPtr) method.

(Inherited from NSObject)
AddObserver(NSObject, String, NSKeyValueObservingOptions, IntPtr)

Registers an object for being observed externally (using string keyPath).   Observed changes are dispatched to the observer’s object ObserveValue(NSString, NSObject, NSDictionary, IntPtr) method.

(Inherited from NSObject)
AddObserver(NSString, NSKeyValueObservingOptions, Action<NSObservedChange>)

Registers an object for being observed externally using an arbitrary method.

(Inherited from NSObject)
AddObserver(String, NSKeyValueObservingOptions, Action<NSObservedChange>)

Registers an object for being observed externally using an arbitrary method.

(Inherited from NSObject)
AllowDeferredLocationUpdatesUntil(Double, Double)

Suggests that location updates are deferred until either distance has been traveled or timeout has passed.

AwakeFromNib()

Called after the object has been loaded from the nib file. Overriders must call base.AwakeFromNib().

(Inherited from NSObject)
BeginInvokeOnMainThread(Action) (Inherited from NSObject)
BeginInvokeOnMainThread(Selector, NSObject)

Invokes asynchrously the specified code on the main UI thread.

(Inherited from NSObject)
Bind(NSString, NSObject, String, NSDictionary) (Inherited from NSObject)
Bind(String, NSObject, String, NSDictionary) (Inherited from NSObject)
BindingInfo(String) (Inherited from NSObject)
BindingOptionDescriptions(String) (Inherited from NSObject)
BindingValueClass(String) (Inherited from NSObject)
CommitEditing() (Inherited from NSObject)
CommitEditing(NSObject, Selector, IntPtr) (Inherited from NSObject)
ConformsToProtocol(IntPtr)

Invoked to determine if this object implements the specified protocol.

(Inherited from NSObject)
Copy()

Performs a copy of the underlying Objective-C object.

(Inherited from NSObject)
DangerousAutorelease() (Inherited from NSObject)
DangerousRelease() (Inherited from NSObject)
DangerousRetain() (Inherited from NSObject)
DidChange(NSKeyValueChange, NSIndexSet, NSString)

Indicates a change occurred to the indexes for a to-many relationship.

(Inherited from NSObject)
DidChange(NSString, NSKeyValueSetMutationKind, NSSet) (Inherited from NSObject)
DidChangeValue(String)

Indicates that a change occurred on the specified key.

(Inherited from NSObject)
DisallowDeferredLocationUpdates()

Turns off deferred background location updates.

DismissHeadingCalibrationDisplay()

Removes the heading calibration view from the display.

Dispose()

Releases the resources used by the NSObject object.

(Inherited from NSObject)
Dispose(Boolean)

Releases the resources used by the CLLocationManager object.

DoesNotRecognizeSelector(Selector)

Indicates that this object does not recognize the specified selector.

(Inherited from NSObject)
Equals(NSObject) (Inherited from NSObject)
Equals(Object) (Inherited from NSObject)
ExposedBindings() (Inherited from NSObject)
GetBindingInfo(NSString) (Inherited from NSObject)
GetBindingOptionDescriptions(NSString) (Inherited from NSObject)
GetBindingValueClass(NSString) (Inherited from NSObject)
GetDictionaryOfValuesFromKeys(NSString[])

Retrieves the values of the specified keys.

(Inherited from NSObject)
GetHashCode()

Generates a hash code for the current instance.

(Inherited from NSObject)
GetMethodForSelector(Selector) (Inherited from NSObject)
GetNativeField(String) (Inherited from NSObject)
GetNativeHash() (Inherited from NSObject)
Init() (Inherited from NSObject)
InitializeHandle(IntPtr) (Inherited from NSObject)
InitializeHandle(IntPtr, String) (Inherited from NSObject)
Invoke(Action, Double) (Inherited from NSObject)
Invoke(Action, TimeSpan) (Inherited from NSObject)
InvokeOnMainThread(Action) (Inherited from NSObject)
InvokeOnMainThread(Selector, NSObject)

Invokes synchrously the specified code on the main UI thread.

(Inherited from NSObject)
IsEqual(NSObject) (Inherited from NSObject)
IsKindOfClass(Class) (Inherited from NSObject)
IsMemberOfClass(Class) (Inherited from NSObject)
IsMonitoringAvailable(Class)

Determines whether the device supports region monitoring for the specified kind of CLRegion.

IsMonitoringAvailable(Type)

Determines whether the device supports region monitoring for the specified kind of CLRegion.

MarkDirty()

Promotes a regular peer object (IsDirectBinding is true) into a toggleref object.

(Inherited from NSObject)
MutableCopy()

Creates a mutable copy of the specified NSObject.

(Inherited from NSObject)
ObjectDidEndEditing(NSObject) (Inherited from NSObject)
ObserveValue(NSString, NSObject, NSDictionary, IntPtr)

Indicates that the value at the specified keyPath relative to this object has changed.

(Inherited from NSObject)
PerformSelector(Selector) (Inherited from NSObject)
PerformSelector(Selector, NSObject) (Inherited from NSObject)
PerformSelector(Selector, NSObject, Double)

Invokes the selector on the current instance and if the obj is not null, it passes this as its single parameter.

(Inherited from NSObject)
PerformSelector(Selector, NSObject, Double, NSString[]) (Inherited from NSObject)
PerformSelector(Selector, NSObject, NSObject) (Inherited from NSObject)
PerformSelector(Selector, NSThread, NSObject, Boolean) (Inherited from NSObject)
PerformSelector(Selector, NSThread, NSObject, Boolean, NSString[]) (Inherited from NSObject)
PrepareForInterfaceBuilder() (Inherited from NSObject)
RemoveObserver(NSObject, NSString)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath.

(Inherited from NSObject)
RemoveObserver(NSObject, NSString, IntPtr)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath and context.

(Inherited from NSObject)
RemoveObserver(NSObject, String)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath.

(Inherited from NSObject)
RemoveObserver(NSObject, String, IntPtr)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath and context.

(Inherited from NSObject)
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.

RespondsToSelector(Selector)

Whether this object recognizes the specified selector.

(Inherited from NSObject)
SetNativeField(String, NSObject) (Inherited from NSObject)
SetNilValueForKey(NSString)

Sets the value of the specified key to null.

(Inherited from NSObject)
SetValueForKey(NSObject, NSString)

Sets the value of the property specified by the key to the specified value.

(Inherited from NSObject)
SetValueForKeyPath(IntPtr, NSString)

A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

(Inherited from NSObject)
SetValueForKeyPath(NSObject, NSString)

Sets the value of a property that can be reached using a keypath.

(Inherited from NSObject)
SetValueForUndefinedKey(NSObject, NSString)

Indicates an attempt to write a value to an undefined key. If not overridden, raises an NSUndefinedKeyException.

(Inherited from NSObject)
SetValuesForKeysWithDictionary(NSDictionary)

Sets the values of this NSObject to those in the specified dictionary.

(Inherited from NSObject)
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.

ToString()

Returns a string representation of the value of the current instance.

(Inherited from NSObject)
Unbind(NSString) (Inherited from NSObject)
Unbind(String) (Inherited from NSObject)
ValueForKey(NSString)

Returns the value of the property associated with the specified key.

(Inherited from NSObject)
ValueForKeyPath(NSString)

Returns the value of a property that can be reached using a keypath.

(Inherited from NSObject)
ValueForUndefinedKey(NSString)

Indicates an attempt to read a value of an undefined key. If not overridden, raises an NSUndefinedKeyException.

(Inherited from NSObject)
WillChange(NSKeyValueChange, NSIndexSet, NSString)

Indicates that the values of the specified indices in the specified key are about to change.

(Inherited from NSObject)
WillChange(NSString, NSKeyValueSetMutationKind, NSSet) (Inherited from NSObject)
WillChangeValue(String)

Indicates that the value of the specified key is about to change.

(Inherited from NSObject)

Events

AuthorizationChanged

Event raised by the object.

DeferredUpdatesFinished

Event raised by the object.

DidDetermineState

Event raised by the object.

DidRangeBeacons

Event raised by the object.

DidStartMonitoringForRegion

Event raised by the object.

DidVisit

Event raised by the object.

Failed

Event raised by the object.

LocationsUpdated

Event raised by the object.

LocationUpdatesPaused

Event raised by the object.

LocationUpdatesResumed

Event raised by the object.

MonitoringFailed

Event raised by the object.

RangingBeaconsDidFailForRegion

Event raised by the object.

RegionEntered

Event raised by the object.

RegionLeft

Event raised by the object.

UpdatedHeading

Event raised by the object.

UpdatedLocation

Event raised by the object.

Extension Methods

ObjectDidBeginEditing(NSObject, INSEditor)
ObjectDidEndEditing(NSObject, INSEditor)
GetValidModes(NSObject, NSFontPanel)
ValidateToolbarItem(NSObject, NSToolbarItem)
GetDebugDescription(INSObjectProtocol)
AcceptsPreviewPanelControl(NSObject, QLPreviewPanel)
BeginPreviewPanelControl(NSObject, QLPreviewPanel)
EndPreviewPanelControl(NSObject, QLPreviewPanel)
GetAccessibilityCustomRotors(NSObject)

Gets the array of UIAccessibilityCustomRotor objects appropriate for this object.

SetAccessibilityCustomRotors(NSObject, UIAccessibilityCustomRotor[])

Sets the array of UIAccessibilityCustomRotor objects appropriate for this object.

Applies to

See also