swiftui - 使用 Swift UI 将 CLLocationManager 的代表放在哪里?
问题描述
多年来我一直在使用 Swift,所以如果我在做一些愚蠢的事情,对不起,Swift UI 的事情也没有帮助我的困惑。我在底部有我正在使用的代码。
所以我正在使用 SwiftUI 制作一个地理围栏应用程序,我已经掌握并运行了基础知识,但仍有一些工作要做,
我在 UserData 环境变量中有地理围栏坐标和东西,我在其他地方得到了一个 json。
拥有一个 SwiftUI 对象,该对象具有当前位置的映射并初始化 CLLocationManager 以处理地理围栏。
我正在尝试在同一个文件上实现委托
locationManager.delegate = self
在 setupManager() 中,
但这会导致
Cannot assign value of type 'GeofencingView' to type 'CLLocationManagerDelegate?'
网上缺乏 SwiftUI 的具体信息似乎是目前最让我困惑的,我认为我应该做的是,
- 创建一个处理委托的自定义 NsObject,但在这种情况下,我不确定如何传递 @EnviromentObject
- 了解如何将委托放在 UIViewRepresentable 对象上。
任何关于我做错了什么的指示将不胜感激。
import SwiftUI
import MapKit
import CoreLocation
struct GeofencingView: UIViewRepresentable {
@EnvironmentObject var userData: UserData
var notification = LocalNotificationManager()
var locationManager = CLLocationManager()
func setupManager() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
self.startGoefenceMonitoring()
}
func startGoefenceMonitoring() {
print("MapListView::startGeofenceMonitoring")
for landmark in self.userData.landmarks {
let moniteringCordinate = CLLocationCoordinate2DMake(landmark.locationCoordinate.longitude, landmark.locationCoordinate.latitude)
let moniteringRegion = CLCircularRegion.init(center: moniteringCordinate, radius: 20.0, identifier: "\(landmark.id)" )
locationManager.startMonitoring(for: moniteringRegion)
}
}
func makeUIView(context: Context) -> MKMapView {
setupManager()
let mapView = MKMapView(frame: UIScreen.main.bounds)
let count = self.userData.landmarks.count
var annotationArray: [MKAnnotation] = []
var num:Int = 0
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
}
struct GeofencingView_Preview: PreviewProvider {
static var previews: some View {
GeofencingView()
.environmentObject(UserData())
}
}
解决方案
推荐阅读
- linux - 最新版本的 wxgtk 3.0 未找到 WXU 3.0.5
- node.js - 写入节点中的文件描述符 3
- javascript - 仅在 jquery ajax 响应的行上显示的数据表
- flutter - 无法在 Flutter 项目中加载资产
- flutter - 即使应用程序被杀死,我也使用广播接收器来获取通知数据,我希望在颤振中具有相同的功能,
- php - SQLSTATE [23000]:违反完整性约束:1048 列“invest_id”不能为空
- android - FragmentScenario 无法按预期工作
- opengl - 了解全向阴影贴图的生成
- python - 如何选择最佳绘图方法
- django - Django模型表单保存