CLLocationManager requestLocation не вызывает didUpdateLocations - PullRequest
0 голосов
/ 22 января 2020

У меня есть простая реализация CLLocationManager, которая работает в одном проекте, но не в моем новом проекте.

Код почти идентичен, но я не могу получить функцию .didUpdateLocations для вызова. Мой код ниже. Есть идеи, почему я не могу заставить работать обновление? Я в растерянности, я создал много приложений, используя службы определения местоположения, и никогда не сталкивался с такой ситуацией.

Также у меня есть три параметра в PLIST, настроенных правильно для Privacy-Location Always et c.

Нет выданных ошибок, просто не вызывается .didUpdateLocations

Класс погоды

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 в главном окне


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

Спасибо за просмотр.

1 Ответ

1 голос
/ 06 февраля 2020

Не видя вашего полного кода главного окна, могу поспорить, что проблема в объеме и жизненном цикле вашего контроллера:

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.
}
...