Ranging for Beacons

Overview

Beacons make location-based products and services available to users by broadcasting information to your device. Ranging is the process of reading the characteristics of a beacon region, such as signal strength, advertising interval, and measured power.

This sample code project configures a device to act as a beacon, and configures a device to use ranging to find surrounding beacons. Use two iOS devices to run the sample, with one acting as a beacon, and the other ranging for the beacon.

Optionally, modify the major and minor value for the beacon, then select the Enabled switch on the configuration screen to start advertising.

ConfigureBeaconViewController.swift contains a view controller object that configures the iOS device running this app to act as a beacon. The configureBeaconRegion() method sets up the region and starts advertising itself.

Configure a Device to Range for Beacons

Using a second iOS device, run the sample app and tap Range for Beacons to scan for beacons. Add a UUID to range for by tapping the Add button in the upper corner of the screen. The hard-coded UUID appears by default.

RangeBeaconViewController.swift contains a view controller object that scans for nearby beacon regions that the user adds. As in any location-based service, first request authorization. Use a CLLocationManager instance to request that authorization, set up the constraint based on the hard-coded UUID, and tell the instance to start monitoring.

self.locationManager.requestWhenInUseAuthorization()
// Create a new constraint and add it to the dictionary.
let constraint = CLBeaconIdentityConstraint(uuid: uuid)
self.beaconConstraints[constraint] = []
/*
By monitoring for the beacon before ranging, the app is more
energy efficient if the beacon is not immediately observable.
*/
let beaconRegion = CLBeaconRegion(beaconIdentityConstraint: constraint, identifier: uuid.uuidString)
self.locationManager.startMonitoring(for: beaconRegion)

While one or more beacons are in range, the locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) delegate method receives their characteristics in the passed array.