swiftxcodeswiftuigeofencing

Geofence didExitRegion is never called


I'm trying to implement Geofencing into an app I'm working on. currently, I'm unable to pass the desired output to the console because didExitRegion is never called.

What might be the cause of this and how may I go about solving it?


import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {

    var locationManager = CLLocationManager()


    func setupManager() {

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()

        // Set Geofencing region
        let geofencingRegion: CLCircularRegion = CLCircularRegion(center: CLLocationCoordinate2DMake(30.510074, 114.330510), radius: 100, identifier: "Wuhan")
        geofencingRegion.notifyOnExit = true
        geofencingRegion.notifyOnEntry = true

        // Start monitoring
        locationManager.startMonitoring(for: geofencingRegion)
    }



    func makeUIView(context: Context) -> MKMapView {
        setupManager()
        let mapView = MKMapView(frame: UIScreen.main.bounds)
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        return mapView
        
    }


    func updateUIView(_ uiView: MKMapView, context: Context) {
    }
}

class MapAppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    var locationManager: CLLocationManager?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        self.locationManager = CLLocationManager()
        self.locationManager!.delegate = self

        return true
    }
}

extension MapAppDelegate{

    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        print("Hello World")
    }

    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        print("Welcome Home")
    }
}

The output I'm getting is multiple iterations of

2020-12-11 18:41:29.916937+0800 Geofencing[4225:235542] [VKDefault] Style Z is requested for an invisible rect

I want to create a state to check whether the user has entered the area or left the area to pull other view controllers on my MainView so I'm starting here.


Solution

  • The reason didExitRegion is never called is that you are not setting the CLLocationManager delegate.

    In MapView you are creating an instance of CLLocationManager and then calling .startMonitoring on this instance. But you never set the delegate on this instance.

    True, you are setting the delegate on the instance you created in your MapAppDelegate, but that is not the instance on which you are calling .startMonitoring.

    You should refactor your code in such a way that you only create a single instance of CLLocationManager, and be sure to set the delegate on that instance.