CLLocationManager 和 iBeacons:是否需要 requestState(for: region)?

CLLocationManager and iBeacons: is requestState(for: region) necessary?

我正在尝试使用 Swift 4 in iOS 10 构建一个 iBeacons 应用程序。许多来源推荐如下:

func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
manager.requestState(for: region)
}

处理应用程序在信标区域内启动时的情况。但是,这种方法在某些情况下似乎会导致副作用和时序错误。

现在,我发现这篇 Whosebug 文章 Understanding iBeacons in iOS 指出,“didDetermineState 仅在您开始监视时自动调用”。

果然,如果我省略了对 requestState(for: region) 的调用,而只调用 locationManager.startMonitoring(for: region) 一切正常!

谁能证实确实如此?如果我调用 startMonitoring 那么就不需要 requestState?

注意:我在开始监控之前将notifyEntryStateOnDisplay设置为true。我想知道这是否与它有关。

是否需要调用 locationManager.requestState(for: region) 完全取决于您的使用情况。

回调locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion)会在以下情况下自动调用:

  1. 当您第一次开始监控时。
  2. 对于所有区域状态更改。这包括 .outside -> .inside、.inside -> .outside 以及与 .unknown
  3. 之间的转换
  4. 每当显示屏亮起时(仅当您设置了监控 BeaconRegion notifyEntryStateOnDisplay=true

因此,如果这些情况对您来说足够了,那么您不需要请求额外的回调。这通常是正确的。

但是,在一些罕见的用例中,明确请求新的回调是有帮助的。也许您的应用程序提供了一个新的视图控制器,然后想以可视化方式向用户显示区域状态。可以在视图加载时调用requestState,然后在回调时更新显示,很方便。

额外回调引起的特定副作用和问题实际上取决于您在回调中放置的内容。如果您在这些回调中开始或停止监控,则创建反馈非常容易导致问题的循环。