向位置管理器请求状态时,CLRegionState即将变为未知状态?

kid*_*d49 1 core-location ios

我在启动区域监视时正在构建与区域监视有关的功能,我在请求状态,如下代码所示。在某些设备上,我一直都在获取区域状态“未知”。如果我打开或关闭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)")
}
Run Code Online (Sandbox Code Playgroud)

Sha*_* TK 6

问题是,您正在requestState使用硬编码延迟-(0.1)进行呼叫。您如何确定位置管理器在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)
   }
}
Run Code Online (Sandbox Code Playgroud)