使用MVVM模式处理SwiftUI和CoreLocation

5
我正在尝试使用MVVM-Pattern将SwiftUI和CoreLocation集成起来。我的LocationManager作为辅助程序工作得很好。但是我该如何更改我的LocationViewModel的属性呢?我在LocationViewModel中实现了我的LocationManager的@ObservedObject。这是我的问题所在。
我不知道如何实现可以在运行时更改属性的属性。我的LocationView中没有任何变化。通过按下按钮一次,一切正常。但是LocationViewModel必须在每次LocationManager更改时更改其属性。
总之,我想显示当前用户的位置。
// Location Manager as Helper

import Foundation
import CoreLocation

class LocationManager: NSObject, ObservableObject {

    let locationManager = CLLocationManager()
    let geoCoder = CLGeocoder()

    @Published var location: CLLocation?
    @Published var placemark: CLPlacemark?

    override init() {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
    }

    func geoCode(with location: CLLocation) {

        geoCoder.reverseGeocodeLocation(location) { (placemark, error) in
            if error != nil {
                print(error!.localizedDescription)
            } else {
                self.placemark = placemark?.first
            }
        }
    }
}

extension LocationManager: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }

        DispatchQueue.main.async {
            self.location = location
            self.geoCode(with: location)
        }

    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        // TODO
    }
}


// Location Model

import Foundation
import CoreLocation

struct Location {
    var location: CLLocation = CLLocation()
    var placemark: CLPlacemark = CLPlacemark()
}

// Location View Model

import SwiftUI
import CoreLocation

class LocationViewModel: ObservableObject {

    @ObservedObject var locationManager: LocationManager = LocationManager()

    @Published var location: Location

    init() {
        self.location = Location()
    }
}

// Location View

import SwiftUI

struct LocationView: View {

    @ObservedObject var locationViewModel: LocationViewModel = LocationViewModel()

    var body: some View {
        VStack(alignment: .leading) {
            Text("Latitude: \(self.locationViewModel.location.location.coordinate.latitude.description)")
            Text("Longitude: \(self.locationViewModel.location.location.coordinate.longitude.description)")
        }
    }
}

struct LocationView_Previews: PreviewProvider {
    static var previews: some View {
        LocationView()
    }
}

更新

现在,我已经设置好了我的MapView

但是我怎么能接收到我的LocationManager的数据呢?didUpdateLocations方法在LocationManager中工作。

所有我尝试做的事情都失败了。我想根据当前用户位置在我的MapView上设置区域。在UIKit中很简单,但在SwiftUI中却非常棘手。

// Map View

import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {

    @ObservedObject var locationManager: LocationManager = LocationManager()

    class Coordinator: NSObject, MKMapViewDelegate {

        var parent: MapView

        init(_ control: MapView) {
            self.parent = control
        }

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView(frame: .zero)
        mapView.delegate = context.coordinator
        return mapView
    }

    func updateUIView(_ mapView: MKMapView, context: Context) {
        mapView.showsUserLocation = true
    }

}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

嗨@Jurie,你找到方法了吗? - Erkam KUCET
1个回答

1

SwiftUI 2

在这种情况下,请使用StateObject

struct LocationView: View {

    @StateObject var locationManager: LocationManager = LocationManager()
    ...

SwiftUI 1

实际上,这里的 LocationViewModel 是多余的。由于您的 LocationManager 是一个 ObservableObject,您可以直接在视图中使用它,如下所示:

struct LocationView: View {

    @ObservedObject var locationManager: LocationManager = LocationManager()

    var body: some View {
        VStack(alignment: .leading) {
            Text("Latitude: \(locationManager.location.coordinate.latitude.description)")
            Text("Longitude: \(locationManager.location.coordinate.longitude.description)")
        }
    }
}

2
没错,这很好用。这个实现符合MVVM模式吗?我正在尝试在SwiftUI中理解这个模式。然而,在这种情况下,它并不容易使用。 - Jurie
这是一个没有VM的MVVM示例。MVVM并不意味着要有一个名为ViewModel的对象,它完全没有SDK或语言绑定支持。 - Jim lai
我认为这更符合 MVVM。 - hariszaman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接