James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Live, Love, Bike, and Code

Share


Tags


iOS iBeacon Background Region Monitoring

Earlier this year when iOS 8 was released I wrote up a quick blog post on how to ensure you can scan for iBeacons with the new CLLocationManager RequestWhenInUseAuthorization flag. However recently I have received a lot of questions about how to scan for iBeacons when the app is in the background or when it has been dismissed completely. Apple has some amazing docs on how this functionality works, but here are the basics.

Monitoring != Ranging

Don’t be confused by these two words. Ranging usually takes place in the foregrounds and allows you to actively scan for beacons, where Monitoring allows you to get notified when the device your app is running on enters or exits a specified beacon region. Monitoring can take place in the background and even if your application is completely dismissed.

Setup

When we create our CLLocationManager we must ensure that we call RequestAlawaysAuthorization(); since we want to always be monitoring. Also ensure you add NSLocationAlwaysUsageDescription to your Info.plist with a message so your users will be asked permission.

When we create our region we must set 3 important flags: NotifyEntryStateOnDisplay, NotifyOnEntry, NotifyOnExit. You can pick and choose between all these, however I usually just set all of them up. Now to specify the functionality to run when a region is entered simply implement the RegionEntered event on your location manager:

Final Checks

Since I am using a local notification we must also ask for permission in iOS 8 by adding this flag in my FinishedLaunching of the AppDelegate:
var settings = UIUserNotificationSettings.GetSettingsForTypes (UIUserNotificationType.Alert, null);<br/>
UIApplication.SharedApplication.RegisterUserNotificationSettings (settings);

It is important to know that iOS gives your app about 10 seconds to run some logic, and if you need more time you will need to spin up a background task, however usually a local notification will work for simple use cases.

Learn More

Be sure to checkout my iBeaconsEverywhere GitHub repository for a full samples and watch my Xamarin Evolve session on using iBeacons on iOS and Android:

Copyright © James Montemagno 2014 All rights reserved. Privacy Policy

View Comments