前段時間寫項目,設計到了通過藍牙ibeacon 的方式接收數據,最開始自己都之前都沒聽過什么叫ibeacon,然后就開始查資料,慢慢的也了解並知道了ibeacon怎么使用了。先大概解釋下ibeacon到底是個什么,在我理解ibeacon可以理解為一個發射信號的基站,類似於移動的信號塔。手機作為一個設備時,進入到了發射基站的信號覆蓋范圍內,那么手機就能夠收到基站發出的信息,這里就是所謂的ibeacon數據。當然也要基站發送數據手機才能夠接受到數據。
下面說說ibeacon的使用。
1 首先需要需要在項目plist 中配置 Privacy - Location Always Usage Description 讓程序允許使用位置
2 要使用ibeacon ,需要在項目中導入 CoreLocation 框架
3 實例化一個位置管理者對象,這里叫做 CLLocationManager ,再實例化一個ibeacon 對象: CLBeaconRegion
self.locationmanager = [[CLLocationManager alloc] init];//初始化 self.locationmanager.delegate = self; _locationmanager.distanceFilter=10;//實時更新定位位置 _locationmanager.desiredAccuracy=kCLLocationAccuracyBest;//定位精確度 self.beacon1 = [[CLBeaconRegion alloc] initWithProximityUUID:[[NSUUID alloc] initWithUUIDString:BEACONUUID] identifier:@"media"];//初始化監測的iBeacon信息
[self.locationmanager requestAlwaysAuthorization];
4 當位置管理者的代理被調用,知道了可以時刻使用用戶的位置時然后開始讀取指定beacon的數據
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{ if (status == kCLAuthorizationStatusAuthorizedAlways) { [self.locationmanager startMonitoringForRegion:self.beacon1];//開始 [self.locationmanager startRangingBeaconsInRegion:self.beacon1]; } }
5 當手機進入到了硬件設備的區域之后就會收到硬件設備發出的beacon 信息
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{ //如果存在不是我們要監測的iBeacon那就停止掃描他 if (![[region.proximityUUID UUIDString] isEqualToString:BEACONUUID]){ [self.locationmanager stopMonitoringForRegion:region]; [self.locationmanager stopRangingBeaconsInRegion:region]; } //打印所有iBeacon的信息 for (CLBeacon* beacon in beacons) { NSLog(@"rssi is :%ld-=mj%d-====min%d",beacon.rssi,beacon.major.intValue,beacon.minor.intValue); } }
如果在硬件范圍內,硬件一直在發射信號,那么手機就會一直收到硬件的ibeacon數據