首页 > 解决方案 > 列出您附近的所有信标

问题描述

我正在使用以下代码连接到我的信标。

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        print("viewDidLoad==ViewController")

        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestAlwaysAuthorization()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("didChangeAuthorization")
        if status == .authorizedAlways {
            if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
                if CLLocationManager.isRangingAvailable() {
                    startScanning()
                }
            }
        }
    }

    func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
        print("didRangeBeacons===\(beacons.count)")
        if beacons.count > 0 {
            print("basss---\(beacons[0].proximityUUID)")
            updateDistance(beacons[0].proximity)
        } else {
            updateDistance(.unknown)
        }
    }

    func updateDistance(_ distance: CLProximity) {
        print("updateDistance")
        UIView.animate(withDuration: 0.8) {
            switch distance {
            case .unknown:
                self.view.backgroundColor = UIColor.gray

            case .far:
                self.view.backgroundColor = UIColor.blue

            case .near:
                self.view.backgroundColor = UIColor.orange

            case .immediate:
                self.view.backgroundColor = UIColor.red
            }
        }
    }


    func startScanning() {
        // 39316, 54420, 5268
        let uuid = UUID(uuidString: "86477363-EAB1-4988-AA99-B5C1517008D9")!
        let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 1, minor: 52681, identifier: "MyBeacon")

        locationManager.startMonitoring(for: beaconRegion)
        locationManager.startRangingBeacons(in: beaconRegion)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

这是工作代码。

但是我想列出所有附近的信标。

知道怎么做吗?


当前的问题是我正在告诉要在哪个信标中搜索startScanning

我想要做的是搜索范围内的所有信标并显示它们。

标签: swiftbeacon

解决方案


您可以更改区域定义以不指定主要或次要:

let beaconRegion = CLBeaconRegion(proximityUUID: uuid,  identifier: "MyBeacon")

然后,这将匹配具有该 UUID 的所有信标,无论主要和次要。

如果你想匹配更多的 UUID,你可以构建多达 20 个不同的区域,每个区域都有不同的 UUID,并在所有这些区域上监控和范围。(请务必更改每个区域的标识符参数。)

但是,您可以监控的区域数量有限制(注册监控的第 21 个区域将无效。)。您可以范围的区域数量没有硬性限制,但是一旦超过 100 个左右,您的应用程序性能将显着降低。

不幸的是,无论 UUID 是什么,在 iOS 上都无法设置匹配所有信标的区域。这是 Apple 设计的安全限制,尽管 IMO 很愚蠢。Android、MacOS、Linux 和 Windows 没有这样的限制。


推荐阅读