天天看点

iBeacon在iOS开发中的使用

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size:14px;">之前在做一个台湾银行项目的时候,有用到ibeacon做推送迎宾消息,抽空将Beacon的使用代码,和注意实现记录一下。</span></span>
           

beacon是ios7.0以后引入的低功耗的蓝牙设备,具体历史大家可以去Google一下,我这里只是写一下项目中用到的代码

iOS8.0之前的定位都是只有app在运行的时候才可以定位的,ios8.0以后,开发者在使用定位的时候,可以选择性两种定位方式

1、永久定位,不论app是否在运行,都有权定位,

- (void)requestAlwaysAuthorization __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_8_0) __TVOS_PROHIBITED;

2、运行时定位,在app运行的时候才会使用定位功能

- (void)requestWhenInUseAuthorization __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_8_0);
           

当然对应的也要在info.plist中,加入

NSLocationAlwaysUsageDescription或者

@interface ViewController ()<CLLocationManagerDelegate>//遵守协议
@property(nonatomic,strong)CLLocationManager * locationManager;//管理者
@end
           
- (void)viewDidLoad {
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;//成为协议的代理
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [self.locationManager requestAlwaysAuthorization];//这个方法是ios8.0以后才用的方法,如果,你的app兼容到了7.0,那就要判断当前版本号,否则就crash
    }else{
        [self.locationManager startUpdatingLocation];
    }
    NSUUID * uuid = [[NSUUID alloc]initWithUUIDString:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"];//要检测的Beaocn的UUID
    CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"abcdefg"];//创建有监控的beaocn的对象
//    CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid major:1 minor:2 identifier:@"abcdefg"];//创建带有主要值和次要值的beacon对象
    [self.locationManager startRangingBeaconsInRegion:region];
    [self.locationManager startMonitoringForRegion:region];

    
}
#pragma mark - Location manager delegate
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{
    NSLog(@"beacons.count-->%ld,regionUUID-->%@",beacons.count,region.proximityUUID.UUIDString);//打印检测到beacon的个数和uuid
}
           

主要值和次要值作用:同一个银行可能有多个相同uuid的beacon,那么我们设置办理业务部门的major为1,贷款部门major为2,这样,就可以通过major来判断具体的位置信息

如果你选择的永久定位,那么在有beaocn进入设备的范围时候,app会被唤醒10s左右(可能因为内存紧张时间变短),这时,你可以通过判断是否为自己要检测的beacon,然后处理一些逻辑,例如发送网络请求,或者本地推送一些信息