SwiftUI CLLocationManager didUpdateLocations 没有被调用

问题描述 投票:0回答:0

我有以下 LocationManager 类来获取用户位置以调用另一个方法。问题是 didUpdateLocations Delegate 永远不会被调用。该 App 已获得授权(设置了标识符),启用了位置服务,并且还调用了 startUpdatingLocation 方法。我正在从 SwiftUI 视图的 onAppear 方法调用 fetchLocation 方法。 模拟器(测试位置已设置)和我的实际设备都遇到了这个问题。

class LocationManager: NSObject, CLLocationManagerDelegate {

let manager = CLLocationManager()

func fetchLocation() {
    
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestWhenInUseAuthorization()
    
    if CLLocationManager.locationServicesEnabled(),
       (manager.authorizationStatus == .authorizedAlways || manager.authorizationStatus == .authorizedWhenInUse) {
        
        manager.startUpdatingLocation()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
    if let location = locations.first {
        
        manager.stopUpdatingLocation()
        
        Weather().fetchWeatherData(location: location)
    }
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    
    print(error)
}

我调用方法如下

var body: some View {
            
    ZStack { ... }
    .ignoresSafeArea()
    .onAppear {
        
        LocationManager().fetchLocation()
    }
}
swiftui core-location
© www.soinside.com 2019 - 2024. All rights reserved.