首页 > 解决方案 > 使用 Swift UI 将 CLLocationManager 的代表放在哪里?

问题描述

多年来我一直在使用 Swift,所以如果我在做一些愚蠢的事情,对不起,Swift UI 的事情也没有帮助我的困惑。我在底部有我正在使用的代码。

所以我正在使用 SwiftUI 制作一个地理围栏应用程序,我已经掌握并运行了基础知识,但仍有一些工作要做,

我正在尝试在同一个文件上实现委托

locationManager.delegate = self

在 setupManager() 中,

但这会导致

Cannot assign value of type 'GeofencingView' to type 'CLLocationManagerDelegate?'

网上缺乏 SwiftUI 的具体信息似乎是目前最让我困惑的,我认为我应该做的是,

  1. 创建一个处理委托的自定义 NsObject,但在这种情况下,我不确定如何传递 @EnviromentObject
  2. 了解如何将委托放在 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())
    }
}

标签: swiftuicllocationmanagerswift5geofencing

解决方案


推荐阅读