CLLocationManager requestLocation 不调用 didUpdateLocations

CLLocationManager requestLocation not calling didUpdateLocations

我有一个简单的 CLLocationManager 实现,它在一个项目中有效,但在我的新项目中无效。

代码几乎相同,但我无法调用 .didUpdateLocations 函数。我的代码如下。任何想法为什么我无法使更新工作?我很茫然,我使用定位服务构建了很多应用程序,但从未见过这种情况。

另外,我在 PLIST 中为 Privacy-Location Always 等正确设置了三个设置。

没有给出错误,它只是没有调用 .didUpdateLocations

天气 Class

class DarkSkyWeatherController: UIViewController, CLLocationManagerDelegate {

    var weatherGetterDelegate: DarkSkyWeatherControllerDelegate?
    var locationManager = CLLocationManager()
    var lat = String()
    var long = String()


    func getLocation() {

        // Ask for Authorisation from the User.

         locationManager.requestAlwaysAuthorization()

         // For use in foreground
         locationManager.requestWhenInUseAuthorization()

         if CLLocationManager.locationServicesEnabled() {
             locationManager.delegate = self
             locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
             locationManager.startUpdatingLocation()
         }

        locationManager.delegate = self
        locationManager.requestLocation()

    }


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


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else {return}
        print("locations = \(locValue.latitude) \(locValue.longitude)")


        lat = String(locValue.latitude)
        long = String(locValue.longitude)

        getDarkSkyWeather { (fetchedInfo) in
            if let myFetchedInfo = fetchedInfo {
                self.weatherGetterDelegate?.getMyWeather(weather: myFetchedInfo)
            }
        }
    }

主视图中的ViewDidLoad window


        let weather = DarkSkyWeatherController()
        weather.weatherGetterDelegate = self
        weather.getLocation()

感谢您的关注。

没有看到完整的主要 window 代码,我敢打赌问题出在控制器的范围和生命周期上:

override func viewDidLoad() {
  let weather = DarkSkyWeatherController()
  weather.weatherGetterDelegate = self
  weather.getLocation()
  // Function exits. The weather constant dies off. 
  // This is why you don't get callbacks.
}

改为执行以下操作。

let weather = DarkSkyWeatherController()
override func viewDidLoad() {
  weather.weatherGetterDelegate = self
  weather.getLocation()
  // Function exits, but the weather constant lives on as a field of your main ViewController. You'll get your callbacks now.
}