swift - 地理围栏 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 上拉其他视图控制器,所以我从这里开始。
解决方案
从未调用的原因didExitRegion
是您没有设置CLLocationManager
委托。
在MapView
你创建一个实例CLLocationManager
然后调用.startMonitoring
这个实例。但是您从未在此实例上设置委托。
诚然,您正在为您在 中创建的实例设置委托MapAppDelegate
,但这不是您正在调用的实例.startMonitoring
。
您应该重构您的代码,以便您只创建一个 的实例CLLocationManager
,并确保在该实例上设置委托。
推荐阅读
- python - numpy 元素的内存地址
- javascript - 在函数末尾将 JS 中传入的数组设置为 null 有什么好处吗?
- java - 测试控制器预期为 201,但为 400
- android - Android SDK 在 Linux 上缺少模拟器臂
- django - POST 请求不适用于 Django 表单和 Django 表单集
- javascript - React Router (v.4) 动态路由问题
- java - 更改 SOAP xml 响应中的标签名称(类中的字段和响应中的标签必须不同)
- asp.net-core - Asp.Net Core 3 优雅关闭抛出 OperationCanceledException
- bash - 如何在 bash 中为读取命令设置浮点超时值?
- docker - 在 k8s 中使用没有注册表设置的本地 docker 镜像