What is iBeacon?

IBeacon is a new feature on the mobile device operating system (iOS7) released by apple in September 2013. The way it works is that devices equipped with Bluetooth low-power (BLE) communication use BLE technology to send their own unique ID to the surrounding area, and the application that receives the ID takes some action based on the ID.

From an individual point of view: IBeacon broadcast the signal in all directions, like throwing a stone on the calm water, creating a layer of ripples (commonly known as water waves), the peak of the wave is equivalent to iBeacon’s RSSI(signal intensity indication), the closer to the center of the place the peak is higher (RSSI), The size of this wave crest (RSSI value) is affected by the force (transmitting power) and water quality (surrounding environmental factors) when throwing stones. The farther away from the center point, the more calm the water wave tends to be. Beyond a certain value, the water wave will disappear invisible. Will not receive the iBeacon signal.

From the iOS developer’s perspective: iBeacon is abstracted into the CLBeacon class in the CoreLocation framework. This class has 6 properties, which are:

  • ProximityUUID is an NSUUID that identifies the company. Each iBeacon used by a company or organization should have the same proximityUUID.

  • The value major is used to identify a group of associated beacons. For example, in the scenario of a supermarket chain, the beacon of each store should have the same Major.

  • The minor value is used to distinguish a specific beacon.

  • It’s an enumeration value for proximity.

    typedef NS_ENUM(NSInteger, // within a few centimeters,// within a few meters,// more than 10 meters, In the test, no more than 10 meters is far.Copy the code
  • Accuracy, distance from iBeacon.

  • Rssi, the signal is slightly negative, the signal is stronger as it approaches 0, and the signal strength cannot be obtained when it is equal to 0.

Tip: proximityUUID, Major, and Minor constitute the unique identifier of iBeacon.

Once within range of the iBeacon, the App wakes up (for about 10 seconds), even if it is killed. When necessary, you can use the UIApplication class – (UIBackgroundTaskIdentifier) beginBackgroundTaskWithExpirationHandler: (void (^) (void)) handler; Method to request more background execution time.

Use of iBeacon: we can use iBeacon for indoor location (garage, shopping mall), smart clocking, reminders (when leaving an object, such as home).

Difference between iBeacon and BLE

IBeacon in iOS is a location-based micro-location technology. Although it receives Majro and Minor via bluetooth, they have no relationship with each other in the development project.

IBeacon uses Apple to provide the CoreLocation library, whereas BLE uses the CoreBluetooth library during development. It is clear from the library provided above, especially after iOS8.0 if you want to use iBeacon, you have to ask the user to click whether to allow XXapp to use geolocation. If you do not prompt this sentence when scanning iBeacon for the first time using iOS App, it is impossible to receive iBeacon signal (except under iOS 8.0). If it is BLE, the development process needs to prompt the user to turn on bluetooth, and does not require any other geographical location information.

The use of iBeacon in iOS

Permission to request

In the info. Add NSLocationAlwaysAndWhenInUseUsageDescription plist NSLocationWhenInUseUsageDescription, NSLocationAlwaysUsageDescription, request location permissions.

Open the Background Modes

The relevant code

The import < CoreLocation/CoreLocation. H >.

Initialize the locationManager and beaconRegion.

- (CLLocationManager *)locationManager {
    if(! _locationManager) { _locationManager = [[CLLocationManager alloc] init]; _locationManager.delegate = self; }return _locationManager;
}

- (CLBeaconRegion *)beaconRegion {
    if(! _beaconRegion) { _beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:[[NSUUID alloc] initWithUUIDString:Beacon_Device_UUID] identifier:@"test"];
        _beaconRegion.notifyEntryStateOnDisplay = YES;
    }
    return _beaconRegion;
}
Copy the code

The CLBeaconRegion class provides three initialization methods:

// listen to all Beacon devices under the UUID - (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID identifier:(NSString *)identifier; // Listen for this UUID, All Beacon devices under major - (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID major:(CLBeaconMajorValue)major identifier:(NSString *)identifier; - (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor identifier:(NSString *)identifier;Copy the code

Before starting to monitor, we need to use isMonitoringAvailableForClass whether equipment support, whether to allow access to geographical location.

BOOL availableMonitor = [CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]];
    
if (availableMonitor) {
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    switch (authorizationStatus) {
        case kCLAuthorizationStatusNotDetermined:
            [self.locationManager requestAlwaysAuthorization];
        break;
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
            NSLog(@"Restricted or rejected.");
        break;
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
            [self.locationManager startMonitoringForRegion:self.beaconRegion];
        }
        break; }}else {
    NSLog(@"This device does not support CLBeaconRegion detection");
}
Copy the code

Listening to the way

Areas can be measured in two ways: Monitoring or Ranging

Monitoring: Can be used to be notified when a device enters or exits a geographical area. Using this method, iBeacon can be detected while the application is running in the background, but only 20 region regions can be detected at the same time, and the distance between the device and iBeacon cannot be inferred.

/ / detection area [self locationManager startMonitoringForRegion: beaconRegion]; / / stop the detection area [self locationManager stopMonitoringForRegion: beaconRegion]; / / Monitoring successful corresponding callback function - (void) locationManager: (CLLocationManager *) manager didStartMonitoringForRegion: (CLRegion *)region; // Callback when the device enters the region - (void)locationManager (CLLocationManager *) Manager didEnterRegion (CLRegion *) Region; // Callback when the device exits the region - (void)locationManager (CLLocationManager *) Manager didExitRegion (CLRegion *)region; / / callback when Monitoring errors have an - (void) locationManager: (CLLocationManager *) manager monitoringDidFailForRegion: [nullable CLRegion *)region withError:(NSError *)error;Copy the code

4. Ranging: Used to detect all iBeacons in an area.

/ / detection area [self locationManager startRangingBeaconsInRegion: beaconRegion]; / / stop the detection area [self locationManager stopRangingBeaconsInRegion: beaconRegion]; // Ranging = (void)locationManager (CLLocationManager *)manager didRangeBeacons (NSArray<CLBeacon *> *)beaconsin(void)locationManager (CLLocationManager *) Manager - (void) localmanager (CLLocationManager *)manager rangingBeaconsDidFailForRegion:(CLBeaconRegion *)region withError:(NSError *)errorCopy the code

Callback to the iBeacon region after the process has been killed

// When the program is killed, enter ibeacon, Or this function is called back when the program is running for screen lock/unlock - (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)stateforRegion:(CLRegion *)region
Copy the code

Get more backstage time

When necessary, you can use the UIApplication class – (UIBackgroundTaskIdentifier) beginBackgroundTaskWithExpirationHandler: (void (^) (void)) handler; Method to request more background execution time.

Simulate iBeacon on an iPhone

Any iOS device that supports low-power sharing of data using Bluetooth can be used as an iBeacon.

Import < CoreBluetooth/CoreBluetooth. H > and < > CoreLocation/CoreLocation. H

Run the uuidgen command in the terminal to generate a UUID of 063fa845-f091-4129-937d-2a189a86d844.

In fact, using BLE to simulate beacon equipment to send signals, very simple.

The relevant code

Initialize peripheralManager

self.peripheralManager= [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:nil];
Copy the code

Send a signal

NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:self.UUIDTextField.text]; / / create a beacon area CLBeaconRegion * beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID: proximityUUID major:self.majorTextField.text.integerValue minor:self.minorTextField.text.integerValue identifier:@"test"];
NSDictionary *beaconPeripheraData = [beaconRegion peripheralDataWithMeasuredPower:nil];
    
if(beaconPeripheraData) { [self.peripheralManager startAdvertising:beaconPeripheraData];; // Start broadcasting}Copy the code

Stop broadcasting

[self.peripheralManager stopAdvertising];
Copy the code

Pay attention to the point

  • Requires access to geolocation rights.
  • The device needs to have Bluetooth enabled.
  • Using iOS device analog beacon signal, Home is out after the signal can not be sent.

Demo

The official Demo

Blog Demo

Refer to the article

  • Official Apple Document
  • Summary of iBeacon in iOS
  • How iBeacon works
  • The difference between iBeacon and BLE in ios development