【问题标题】:CLRegionState is coming Unknown while requesting a state from the location manager?CLRegionState 在向位置管理器请求状态时出现未知?
【发布时间】:2018-05-29 10:54:33
【问题描述】:

我正在构建与区域监控相关的功能,同时开始区域监控我正在请求如下代码所示的状态。在某些设备上,我一直在获取区域状态未知。如果我打开或关闭 Wifi 或将充电器插入其中。它开始正常工作。 如何使其在蜂窝网络上更可靠? 请注意,在进行任何区域监控或状态请求调用之前,我从用户那里获得了所有位置权限。

private func initiateLocationManager() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.distanceFilter = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
}

func startMonitoring(alarm: StationAlarm) {
    if LocationManager.sharedInstance.isRegionMonitoringAvailable() {
        let coordinate = CLLocationCoordinate2D(latitude: stationLatitude, longitude: stationLongitude)

        // 1
        let region = CLCircularRegion(center: coordinate, radius: CLLocationDistance(radius * 1000), identifier: alarm.alarmId)

        // 2
        region.notifyOnEntry = true
        region.notifyOnExit = false

        // 4
        locationManager.startMonitoring(for: region)
        Utility.delay(0.1) { [weak self] in
            self?.locationManager.requestState(for: region)
        }

    }
}

func locationManager(_: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
    Log.event("Region State is \(state.rawValue)")
}

【问题讨论】:

  • @Honey 但我不是在等待进入或退出通知。之后我只是请求了该区域的现有状态,调用开始监控。
  • 是的,但是您的 wifi 已关闭。我只是想指出:“如果禁用 Wi-Fi,则区域监控的准确性会大大降低。”并且可能会导致它不为人知......
  • @Honey 即使有时它也会发生在 Wifi 中。
  • 1.我猜这是因为地理围栏的质量。您是否看到该链接问题的其他答案? 2. AFAIK 你真的不应该关心它的状态,而只是关心它是否进入/退出了一个区域

标签: ios core-location


【解决方案1】:

问题是,您正在使用硬编码延迟 - (0.1) 调用 requestState。您如何确保位置管理器在 0.1 秒内开始监控您的区域?仅当开始对其进行监视时,您才能获得区域的确切区域状态。

克服这个问题的更好方法是,实现didStartMonitoringForRegion委托并调用requestStateForRegion

locationManager.startMonitoring(for: region)

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

func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
   if (region is CLBeaconRegion) && state == .inside {
      locationManager(manager, didEnterRegion: region)
   }
}

【讨论】:

    【解决方案2】:

    来自CLLocationManager requestState(for:) docs

    地区:您想了解其状态的地区。该对象必须是 Map Kit 提供的标准区域子类之一的实例。 您不能使用此方法来确定您自己定义的自定义区域的状态。

    您自己定义了该区域,因此您不能使用requestState(for:) 来获取其状态。您可以将该函数用于从核心位置返回的区域(通过委托方法)。

    如果您想知道设备当前是否在某个区域内,请启动标准位置更新请求(startUpdatingLocation() 等),当您返回最近且准确的坐标时,使用 CLCircularRegioncontains() 函数检查坐标。

    // In the locationManager(_:didUpdateLocations:) delegate method
    if myCircularRegion.contains(myCoordinate) {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2016-12-11
      • 2014-03-07
      • 2014-07-18
      • 2019-08-17
      • 1970-01-01
      • 2016-06-05
      相关资源
      最近更新 更多