iOS蓝牙开发之iBeacon

1. iBeacon的使用

1、iBeacon的使用是基于蓝牙和定位的,所以我们需要先到入两个库:

#import 
#import 

在iOS8之后,苹果改变了定位的开启方式,需要在plist文件中加入字段NSLocationAlwaysUsageDescription(允许一直开启定位)


129603-ab293305d84223f4.png.jpg

2.直接上代码,以下代码包含广播自身与搜索附近广播:

#define UUID [[NSUUID alloc]initWithUUIDString:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"] // uuid可替换为自己需要的

@interface ViewController ()

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLBeaconRegion *beaconRegion;
@property (strong, nonatomic) CBPeripheralManager *peripheraManager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self beaconBroadCasting]; // 广播自身
    [self beaconMonitoring]; // 扫描附近广播
}
#pragma mark - BroadCast
- (void)beaconBroadCasting{
    // 创建并广播信号
    if (!_peripheraManager)
    {
        _peripheraManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    }
    else
    {
        _peripheraManager.delegate = self;
    }
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
        NSDictionary *peripheralData = nil;
        CLBeaconRegion * region = [[CLBeaconRegion alloc] initWithProximityUUID:UUID major:0 minor:1 identifier:[UUID UUIDString]];// UUID、major、minor将会在后面解释
        peripheralData = [region peripheralDataWithMeasuredPower:nil];
        if(peripheralData)
        {
            [self.peripheraManager startAdvertising:peripheralData];
        }
    }
}

#pragma mark - Monitor
- (void)beaconMonitoring{
    self.beaconRegion = [[CLBeaconRegion alloc]initWithProximityUUID:UUID identifier:[UUID UUIDString]];
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
// 发现有iBeacon设备进入扫描范围回调
}

- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{
// 扫描到iBeacon设备回调,扫描到的beacon存在数组beacons中
// 打印iBeacon信息
    for (CLBeacon *beacon in beacons) {
    // iBeacon参数将在后面介绍
    }
}

2.iBeacon的参数

uuid 唯一标识,唯一标识此类iBeacon
major 主要值
minor 次要值
主要值与次要值能够使你区分使用相同UUID的不同iBeacon设备。(在将手机模拟为iBeacon广播时,可将一些信息作为major或者minor广播)注意major与minor为16 位无符号整数。
proximity 远近范围,包含三种情况:
CLProximityFar 10米以外
CLProximityImmediate 几米范围之内
CLProximityNear 几厘米范围内
rssi 信号强度,为负值,越接近0表示信号强度越大,距离越近

你可能感兴趣的:(iOS蓝牙开发之iBeacon)