Swift 4 locationManager didEnterRegion doesn't fire when user is in region on app launch

1.2k views Asked by At

I'm trying to detect, if a user is entering a specific region in my app.

This works fine, if the user isn't in the specific region when the app launches and then enters the region.

But if the user is in the specific region when the app launches, the "didEnterRegion" function is not being triggered.

Here's my code:

override func viewDidLoad() {
    super.viewDidLoad()
    self.dbRef = Database.database().reference()
    self.mapView.delegate = self
    self.initLocationManager()
    guard let userLocation = locationManager.location?.coordinate else {return}
    self.userLocation = userLocation
    let region = MKCoordinateRegion(center: userLocation, latitudinalMeters: 1200, longitudinalMeters: 1200)
    mapView.setRegion(region, animated: true)
    self.getPlaces { (places) in
        self.places = places
        self.addAnnotationsToMap(places)
        if(CLLocationManager.authorizationStatus() == .authorizedAlways){
            if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){
                for place in places{
                    self.startMonitoring(place)
                }
            }
        }
    }
}

func startMonitoring(_ place: Place){
    let region = CLCircularRegion(center: place.getCoordinate(), radius: 50, identifier: place.identifier)
    region.notifyOnEntry = true
    region.notifyOnExit = true
    locationManager.startMonitoring(for: region)
}

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    print("Entered Region : \(region.identifier)")
}
1

There are 1 answers

1
Siyu On BEST ANSWER

This is expected behavior, as the name suggests, it is triggered only at region broader crossing. If you want to determine whether the user is inside or outside a region use locationManager.requestState(for region: CLRegion) then receive the result in delegate function locationManager(_:didDetermineState:for:)

To query for all monitored regions, call requestState(region) for every object in locationManager.monitoredRegions.