Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLRegionState is coming Unknown while requesting a state from the location manager?

I am building a feature related to region monitoring while starting region monitoring I am requesting the state as shown below in code. On some of the devices, I am getting region state Unknown all the time. If I switch Wifi On or Off or plug the charger into it. It starts working fine. How can I make it more reliable on a cellular network? Please, note I took all location permissions from the user before making any region monitoring or state request calls.

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)")
}
like image 837
kidsid49 Avatar asked Dec 09 '25 17:12

kidsid49


1 Answers

The issue is, you are calling the requestState using a hard-coded delay - (0.1). How do you make sure the Location Manager started monitoring your region within 0.1 seconds? You will get the exact region state of a region, only if started monitoring it.

The better method for overcoming this problem is, implement the didStartMonitoringForRegion delegate and call 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)
   }
}
like image 102
Shamsudheen TK Avatar answered Dec 11 '25 09:12

Shamsudheen TK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!