Create Geofence

PDF for offline use
Sample Code:

Let us know how you feel about this

Translation Quality


0/250

Geofences let you track a user's movement in and out of a geographical region. This recipe explains how to set up a simple geofence.

Recipe

Geofences work by specifying a circular region - CLCircularRegion - and firing an event when the user crosses the CLCircularRegion's boundary. A geofence subscribes to updates from the system's location manager, and will wake an application in the background to handle a boundary crossing event.

  1. Geofencing requires the CoreLocation library, so we'll start by adding the using directive:
using CoreLocation;
  1. Next, let's create an instance of the CLLocationManager class to interact with system location services:
var LocMgr = new CLLocationManager();
  1. Starting with iOS 8, applications must call requestWhenInUseAuthorization on CLLocationManager in order to gain access to the user's application. If the app hasn't been granted permission before, the user will be prompted to allow or deny access.
LocMgr.requestAlwaysAuthorization(); //to access user's location in the background
  LocMgr.requestWhenInUseAuthorization(); //to access user's location when the app is in use.
  1. In addition to explicitly requesting access to the user's location, you must add two keys to the Info.plist file, by opening Info.plist and selecting Source.
  • NSLocationWhenInUseUsageDescription - A description of why your app wants to access the user's location in the foreground.
  • NSLocationAlwaysInUsageDescription - A description of why your app wants to access the user's location in the background.
  1. Next, we'll create a CLCircularRegion to track. We define a CLCircularRegion by specifying a center coordinate, a radius and a string identifier:
CLCircularRegion region = new CLCircularRegion(new CLLocationCoordinate2D(+37.29430502,-122.09423697), 10129.46, "Cupertino");
  1. Not all devices have geofencing enabled, so before we begin monitoring, we'll want to check if location monitoring is available by calling the CLLocationManager's IsMonitoringAvailable method, passing in CLCircularRegion as the Type. We can subscribe to three updates from our LocMgr: RegionEntered and RegionLeft to track the user's movement, and DidStartMonitoringRegion to let us know when a geofence has been established. The code example below shows us subscribing to all three events:
if (CLLocationManager.IsMonitoringAvailable (typeof(CLCircularRegion))) {

  LocMgr.DidStartMonitoringForRegion += (o, e) => {
    Console.WriteLine ("Now monitoring region {0}", e.Region.ToString ());
  };

  LocMgr.RegionEntered += (o, e) => {
    Console.WriteLine ("Just entered " + e.Region.ToString ());
  };

  LocMgr.RegionLeft += (o, e) => {
    Console.WriteLine ("Just left " + e.Region.ToString ());
  };

  LocMgr.StartMonitoring (region);

  } else {
  Console.WriteLine ("This app requires region monitoring, which is unavailable on this device");
  }
  1. Once we've subscribed to events, we can call StartMonitoring on the LocMgr, passing in a CLCircularRegion, as illustrated by the code above.
  2. To stop monitoring a region, call StopMonitoring on the LocMgr:
if (CLLocationManager.IsMonitoringAvailable (typeof(CLCircularRegion))) {
      LocMgr.StopMonitoring (region);
      Console.WriteLine ("Stopped monitoring region: {0}", region.ToString ());
    } else {
      Console.WriteLine ("This app requires region monitoring, which is unavailable on this device");
    }
  1. Running the application should produce the following output:
Now monitoring region CLCircularRegion (identifier:'Cupertino', center:<+37.29430502,-122.09423697>, radius:10129.46m)
      Just entered CLCircularRegion (identifier:'Cupertino', center:<+37.29430502,-122.09423697>, radius:10129.46m)
      Just left CLCircularRegion (identifier:'Cupertino', center:<+37.29430502,-122.09423697>, radius:10129.46m)

To test geofences in the iOS simulator, refer to the Test Location Changes in Simulator recipe.

Additional Information

While the code above will run in most situations, iOS location services require several more checks to ensure our geofencing application will run properly. First, we need to check if Location Services are enabled on the device by running CLLocationManager.LocationServicesEnabled. Then, we should ensure that the user has authorized our application access to their location by checking the value of CLLocationManager.Status, as illustrated by the code sample below:

if (CLLocationManager.LocationServicesEnabled) {

  if (CLLocationManager.Status != CLAuthorizationStatus.Denied) {

    if (CLLocationManager.IsMonitoringAvailable (typeof(CLCircularRegion))) {

      LocMgr.StopMonitoring (region);
      Console.WriteLine ("Stopped monitoring region: {0}", region.ToString ());

    } else {
      Console.WriteLine ("This app requires region monitoring, which is unavailable on this device");
    }

    LocMgr.Failed += (o, e) => {
      Console.WriteLine (e.Error);
    };

  } else {
    Console.WriteLine ("App is not authorized to use location data");
  }

} else {
  Console.WriteLine ("Location services not enabled, please enable this in your Settings");
}

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.