Geofence didExitRegion 永远不会被调用

Geofence didExitRegion is never called

我正在尝试将地理围栏实现到我正在开发的应用程序中。目前,我无法通过 所需的输出到控制台,因为从未调用 didExitRegion

这可能是什么原因造成的,我该如何解决?


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")
    }
}

我得到的输出是

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

我想创建一个状态来检查用户是否进入该区域或离开该区域以拉动我的 MainView 上的其他视图控制器,所以我从这里开始。

从未调用 didExitRegion 的原因是您没有设置 CLLocationManager 委托。

MapView 中,您正在创建 CLLocationManager 的实例,然后在该实例上调用 .startMonitoring。但是您从未在此实例上设置委托。

是的,您在 MapAppDelegate 中创建的实例上设置委托,但这不是您调用 .startMonitoring 的实例。

您应该以只创建 CLLocationManager 的单个实例的方式重构您的代码,并确保在该实例上设置委托。