且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有ViewControllers的情况下使用SwiftUI获取当前位置?

更新时间:2022-05-30 22:13:47

您可以创建 LocationManager $ c的 ObservedObject $ c>通过实现 ObservableObject 协议。

You could create an ObservedObject of your LocationManager by implementing the ObservableObject protocol.

通过 @Published 属性,您可以创建一个发布者对象,当该对象内部发生某些更改时,该对象将通知观察者(在这种情况下,是您的视图)。

With the @Published attribute you can create a publisher object which notify the observers (your view, in this case) when something changes inside that object.

这就是为什么在我的LocationManager中我在这些变量中添加了 @Published 属性:

That's why in my LocationManager I added the @Published attribute to those var:


  1. locationStatus:CLAuthorizationStatus?它包含从 didChangeAuthorization 委托方法
  2. 收到的值
  3. lastLocation: CLLocation?它包含由 didUpdateLocations 委托方法

  1. locationStatus: CLAuthorizationStatus? it contains the value received from didChangeAuthorization delegate method
  2. lastLocation: CLLocation? it contains the last location calculated by the didUpdateLocations delegate method


$计算的最后一个位置b $ b

LocationManager



LocationManager

import Foundation
import CoreLocation
import Combine

class LocationManager: NSObject, ObservableObject {

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

    @Published var locationStatus: CLAuthorizationStatus? {
        willSet {
            objectWillChange.send()
        }
    }

    @Published var lastLocation: CLLocation? {
        willSet {
            objectWillChange.send()
        }
    }

    var statusString: String {
        guard let status = locationStatus else {
            return "unknown"
        }

        switch status {
        case .notDetermined: return "notDetermined"
        case .authorizedWhenInUse: return "authorizedWhenInUse"
        case .authorizedAlways: return "authorizedAlways"
        case .restricted: return "restricted"
        case .denied: return "denied"
        default: return "unknown"
        }

    }

    let objectWillChange = PassthroughSubject<Void, Never>()

    private let locationManager = CLLocationManager()
}

extension LocationManager: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        self.locationStatus = status
        print(#function, statusString)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.lastLocation = location
        print(#function, location)
    }

}



视图



在您的视图中,您只需要创建 LocationManager 标记为 @ObservedObject

import SwiftUI

struct MyView: View {

    @ObservedObject var locationManager = LocationManager()

    var userLatitude: String {
        return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
    }

    var userLongitude: String {
        return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
    }

    var body: some View {
        VStack {
            Text("location status: \(locationManager.statusString)")
            HStack {
                Text("latitude: \(userLatitude)")
                Text("longitude: \(userLongitude)")
            }
        }
    }
}

struct MyView_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
    }
}