SwiftUI Live 位置更新

SwiftUI Live location update

我已经在我的一个 ObservableObject 中实现了 CLLocationManagerDelegate,我希望在位置发生变化时得到通知。一切正常,但我打印了一次“位置已更改”。我的猜测是我应该从外面打电话给 manager.startUpdatingLocation(),但我不知道具体从哪里打电话。

import CoreLocation
import Combine

class LocationManagerService: NSObject, ObservableObject, CLLocationManagerDelegate {
    var manager: CLLocationManager = CLLocationManager()
    @Published var location: CLLocation?
    @Published var enabled: Bool = false
    
    override init() {
        super.init()
        manager.delegate = self
        
        if CLLocationManager.locationServicesEnabled() {
            manager.requestWhenInUseAuthorization()
            // manager.requestAlwaysAuthorization()
            manager.startUpdatingLocation()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("location changed") // prints only once
        location = locations.first
        manager.stopUpdatingLocation()
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        enabled = CLLocationManager.locationServicesEnabled()
    }
}

注释掉停止更新的这一行

location = locations.first 
manager.stopUpdatingLocation() // this