本文主要介绍蓝牙开发中基于iBeacon的开发。文章中如有错误的地方,请大神指正。如有不太懂的地方请留言,我将及时回复。
监听Beacon 主要有三个参数UUID,Major,Minor。均可由硬件工程师定义。UUID可理解为用于识别其为哪一种类的Beacon,Major和Minor一起可用来确定这个种类的Beacon中某一Beacon的唯一性。
下面直接说代码部分。
首先导入iBeacon开发中需要的系统库CoreLocation,导入方式@import CoreLocation。
然后在plist文件中加入一下4个键值对。
Privacy - Location When In Use Usage Description------Need location when in used
Privacy - Location Always Usage Description------Need location always
Privacy - Location Usage Description------Need location
Privacy - Bluetooth Peripheral Usage Description------是否允许此App使用蓝牙?
写一个用来处理Beacon相关事情的类LocationManager。
主要方法:
//设置代理 开启监控
-(void)startUpdatingLocation:(UIApplication *)application
{
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
}
//监控信标监控信标
+ (void)updateMonitoredRegion:(NSString *)iuuid :(unsigned short)imajor :(unsigned short)iminor
{
CLBeaconRegion *region;
NSString *str=[NSString stringWithFormat:@"%@%u%u",iuuid,imajor,iminor];
NSUUID *uuid=[NSUUID new];
region = nil;
if(iuuid && imajor && iminor)
{
region = [[CLBeaconRegion alloc] initWithProximityUUID:[uuid initWithUUIDString:iuuid] major:imajor minor:iminor identifier:str];
}else if (iuuid) {
region=[[CLBeaconRegion alloc] initWithProximityUUID:[uuid initWithUUIDString:iuuid] identifier:str];
}
if(region)
{
region.notifyOnEntry = YES;
region.notifyOnExit = YES;
[[LocationManager getInstance].locationManager startMonitoringForRegion:region];
[[LocationManager getInstance].locationManager startRangingBeaconsInRegion:region];
}
}
CoreLocation库提供的俩个系统回调函数
//离开或进入所监控的信标范围时调用
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
//一直调用 返回手机或者其他设备蓝牙范围内所有被监控的信标
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
下面附上一个小demo
网友评论