iBeacon的使用

2019-06-10  本文已影响0人  coldprince

一、iBeacon简介


二、搜索附近iBeacon设备列表

1.与蓝牙设备的不同
2. CLBeaconRegion类与iBeacon
let beaconRegion1 = CLBeaconRegion(proximityUUID: proximityUUID, identifier: "com.mycompany.myregion")
3.检查信标区域监测的可用性

获取iBeacon设备列表使用authorizedWhenInUse权限即可。

//设备是否支持使用指定类进行区域监测
let isMonitoringAvailable = CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self)
if isMonitoringAvailable == true {
    //APP是否取得定位权限
    locationManager = CLLocationManager()
    locationManager.delegate = self
    let authorizationStatus = CLLocationManager.authorizationStatus()
    if authorizationStatus == .notDetermined {
        locationManager.requestWhenInUseAuthorization()
    }
}
4.获取定位权限后,开始扫描指定UUID的iBeacons
locationManager.startRangingBeacons(in: beaconRegion1)
5.在CLLocationManagerDelegate的代理方法中获取扫描到的iBeacons
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
    for beacon in beacons {
        print("\(beacon.proximityUUID)+++\(beacon.major)+++\(beacon.minor)+++\(beacon.rssi)+++\(beacon.accuracy)")
    }
}

三、监听某一iOS设备进入或离开信标区域

1. 同二、2
2. 同二、3
3. 检查信标区域监测的可用性

监听进入或离开信标区域需要使用authorizedAlways权限。

4.获取定位权限后,开始监听指定UUID的iBeacons
locationManager.startMonitoring(for: beaconRegion1)
5.CLLocationManagerDelegate的代理方法
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
    // 异步获取region的状态
    locationManager.requestState(for: beaconRegion1)
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
    if state == .inside {
        print("已进入监测区域")
    }
    else {
        //...
    }
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
  print("已进入监测区域")
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
  print("已离开监测区域")
}
\color{red}{6.注意}

如果在iBeacon覆盖范围内或覆盖范围外启动startMonitoring,那么didDetermineState可能不会立即反映出当前所处的位置状态(didEnterRegion和didExitRegion都不会正确调用),需要等待app在当前位置运行一会才会有效。

上一篇 下一篇

猜你喜欢

热点阅读