首页 > 解决方案 > iBeacon 约束接受多个主要/次要

问题描述

我遵循了一个在线教程,并且在我的项目中使用了以下代码,它可以检测到具有特定 uuid/major/minor 的 iBeacon 并对其进行一些逻辑处理。我想知道是否有一种方法可以接受多个 uuid 或多个主要/次要并将它们传递给其他功能?这是我到目前为止的代码:

class BeaconDetector: NSObject, ObservableObject, CLLocationManagerDelegate {
    var locationManager: CLLocationManager?
    @Published var lastDistance = CLProximity.unknown
    
    override init(){
        super.init()
        locationManager = CLLocationManager()
        locationManager?.delegate = self
        locationManager?.requestAlwaysAuthorization()
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus){
        if status == .authorizedAlways{
            if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
                if CLLocationManager.isRangingAvailable(){
                    startScanning()
                }
            }
        }
    }
    
    func startScanning(){
        let uuid = UUID(uuidString: "2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6")!
        let constraint = CLBeaconIdentityConstraint(uuid: uuid, major: 0, minor: 0)
        let beaconRegion = CLBeaconRegion(beaconIdentityConstraint: constraint, identifier: "MyBeacon")
        locationManager?.startMonitoring(for: beaconRegion)
        locationManager?.startRangingBeacons(satisfying: constraint)
    }
    
    func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
        if let beacon = beacons.first{
            update(distance: beacon.proximity)
        } else{
            update(distance: .unknown)
        }
    }
    
    func update(distance: CLProximity) {
        lastDistance = distance
    }
    
}

我想我知道如何通过将值添加到更新函数来传递值,但是我如何能够检测和接受多个信标将是我现在最大的问题,谢谢!

标签: iosswiftcore-locationibeacon

解决方案


您可以在位置管理器中为最多 20 个区域设置位置监控。这些区域可以是基于 GPS 的地理围栏区域或“信标区域”,也可以是两者的任意组合,但您限制为 20 个。要注册多个信标区域,您只需多次调用您的locationManager?.startMonitoring(for: beaconRegion)代码。

创建信标区域时,您必须指定 UUID。您可以将其设为特定的 UUID 和通配符主要/次要,特定的 UUID 以及主要和通配符次要,或 UUID、主要和次要 ID 的特定值。(我不记得你是否可以指定 UUID 和 minor 并让它适用于任何专业。已经有一段时间了。)

如果您对主要或次要 ID 使用通配符,系统会将任何匹配的设备视为同一区域的一部分,您必须编写代码来确定检测到的特定信标。我似乎记得,一旦您进入带有通配符的区域(例如特定的 UUID 和任何主要或次要),那么如果检测到具有不同主要/次要的第二个信标,您将不会收到新的“进入区域”通知. 这被视为同一区域的一部分。在这种情况下,您需要开始收听特定的信标通知并查看您为每个信标获得的值。


推荐阅读