首页 > 解决方案 > 地理围栏 didExitRegion 从未被调用

问题描述

我正在尝试将地理围栏实现到我正在开发的应用程序中。目前,我无法将所需的输出传递给控制台,因为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 上拉其他视图控制器,所以我从这里开始。

标签: swiftxcodeswiftuigeofencing

解决方案


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

MapView你创建一个实例CLLocationManager然后调用.startMonitoring这个实例。但是您从未在此实例上设置委托。

诚然,您正在为您在 中创建的实例设置委托MapAppDelegate,但这不是您正在调用的实例.startMonitoring

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


推荐阅读