How to use ibeacon in IOS


What is ibeacon?

iBeaconIt is a new feature on IOS (IOS 7) released by apple in September 2013. Its working mode is to use the device equipped with low power Bluetooth (ble) communication functionBLETechnology sends its own unique ID to the surrounding, and the application software that receives the ID will take some actions according to the ID.

From a personal point of view: iBeaconBroadcasting signals in all directions is like throwing a stone on the calm water, creating layers of ripples (commonly known as water waves), with a peak equivalent to the height of ibeaconRSSI(receiving signal strength indication), the higher the peak is near the center point (the larger the RSSI). The size of the peak (the value of RSSI) is affected by the force (emission power) and water quality (environmental factors) when throwing stones. The farther away from the center point, the more calm the water wave tends to be. If it exceeds a certain value, the water wave will disappear, That is to say, the distance of ibeacon’s outward broadcast has a range. Beyond this range, ibeacon’s signal will not be received.

From the perspective of IOS developers:Ibeacon inCoreLocationAbstract asCLBeaconClass, which has six properties, namely:

  • proximityUUIDIt’s aNSUUIDTo identify the company. Every company and organization should have the same ibeaconproximityUUID
  • major, main value, which is used to identify a group of associated beacons. For example, in a supermarket chain scenario, each branch’s beacon should have the same valuemajor
  • minor, secondary value, which is used to distinguish a particular beacon.
  • proximity, near far range, an enumeration value.
  • typedef NS_ENUM(NSInteger, CLProximity) {
    	Clproximityunknown, // invalid
    	Clproximityimmediate, // within a few centimeters
    	Clproximitynear, // within a few meters
    	Clproximityfar // if it is more than 10 meters away, but in the test, if it is less than 10 meters away, it is a far
  • accuracy, the distance from ibeacon.
  • rssiThe closer to 0, the stronger the signal. When it is equal to 0, the signal strength cannot be obtained.

Tip:proximityUUIDmajorminorThese three attributes are composed ofiBeaconUnique identifier of the.

Just enteriBeaconYou can wake up the app (about 10 seconds), even if the program is killed. If necessary, it can be usedUIApplicationClass- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler;Method to request more background execution time.

The use of ibeaconWe can useiBeaconIt can be used for indoor positioning (garage, shopping mall), intelligent clock in and reminder (when leaving something, such as leaving home).

The difference between ibeacon and ble

In IOS, ibeacon is a micro positioning technology based on geographical location, although it can be received by mobile phone BluetoothMajroMinorBut they have nothing to do with development engineering.

iBeaconUse apple to provideCoreLocationLibrary, however, is used in the development process of bleCoreBluetoothLibrary. It’s very clear from the library provided above, especially if you want to use it after IOS 8.0iBeacon, the user must click whether to allow or notXXappUse geographic location. If you scan with IOS app for the first timeiBeaconIt is impossible to receive this sentence without promptiBeacon(except under IOS 8.0). If it is ble, the user will be prompted to open Bluetooth in the development process, and no other geographic location information is required.

Application of ibeacon in IOS

Permission request

stayinfo.plistAdd inNSLocationAlwaysAndWhenInUseUsageDescription,NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription, request geographic permission.

openBackground Modes

Related codes

import <CoreLocation/CoreLocation.h>


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

CLBeaconRegionClass, which provides three initialization methods:

//Monitor all beacon devices under the UUID
- (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID identifier:(NSString *)identifier;

//Listen to all beacon devices under UUID, major
- (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID major:(CLBeaconMajorValue)major identifier:(NSString *)identifier;

//Listen to the only beacon device
- (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor identifier:(NSString *)identifier;

Before we start monitoring, we need to use theisMonitoringAvailableForClassDetermine whether the device supports and allows access to geographic location.

BOOL availableMonitor = [CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]];

if (availableMonitor) {
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    switch (authorizationStatus) {
        case kCLAuthorizationStatusNotDetermined:
            [self.locationManager requestAlwaysAuthorization];
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
            Nslog (@ "restricted or rejected");
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
            [self.locationManager startMonitoringForRegion:self.beaconRegion];
} else {
    Nslog (@ "the device does not support clbeacon region detection");

Monitoring mode

The area can be detected in two waysMonitoringorRangingmode

Monitoring: it can be used to get notification when a device enters / exits a geographical area. Using this method, ibeacon can be detected when the application runs in the background, but only 20 regions can be detected at the same time, and the distance between the device and ibeacon cannot be inferred.

//Start detection area
[self.locationManager startMonitoringForRegion:beaconRegion]; 

//Stop detection area
[self.locationManager stopMonitoringForRegion:beaconRegion]; 

//Monitoring success corresponds to callback function
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region;

//Callback when the device enters the area
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region;

//Callback when the device exits the zone
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region;

//Callback when monitoring error occurs
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(nullable CLRegion *)region withError:(NSError *)error;

Ranging: can be used to detect all ibeacons in a region.

//Start detection area
[self.locationManager startRangingBeaconsInRegion:beaconRegion];

//Stop detection area
[self.locationManager stopRangingBeaconsInRegion:beaconRegion];

//The success of ranking corresponds to the callback function
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray<CLBeacon *> *)beacons inRegion:(CLBeaconRegion *)region 

//Callback when an error occurs in ranking
- (void)locationManager:(CLLocationManager *)manager rangingBeaconsDidFailForRegion:(CLBeaconRegion *)region withError:(NSError *)error

After process kill, enter the callback in ibeacon area

//When the program is killed, enter ibeacon area, or lock / unlock the screen when the program is running, this function will be called back
- (void)locationManager:(CLLocationManager *)manager
      didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region

More backstage time

If necessary, it can be usedUIApplicationClass- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler;Method to request more background execution time.

[simulate ibeacon with iPhone]

Any IOS device that supports Bluetooth for low-power data sharing can be used as aiBeacon

import <CoreBluetooth/CoreBluetooth.h>and<CoreLocation/CoreLocation.h>

stayterminalUsed inuuidgenCommand to generate a UUID063FA845-F091-4129-937D-2A189A86D844

In fact, the use ofBLETo simulate the beacon device to send signals, very simple.

Related codes


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

Send a signal

NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:self.UUIDTextField.text];
//Create a beacon zone
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 startAd vertising:beaconPeripheraData ];;// Start broadcasting

Stop broadcasting

[self.peripheralManager stopAdvertising];

Pay attention

  • Geographic access is required.
  • The device needs to turn on Bluetooth.
  • Using IOS device to simulate beacon signal, home can’t send signal after going out.

The above is how to use ibeacon in IOS. For more information about ibeacon in IOS, please pay attention to other related articles of developer!