locationManager.location всегда ноль - PullRequest
0 голосов
/ 03 сентября 2018

Я практически снял этот код с интернета:

//variables
//location manager
var locationManager:CLLocationManager!
var currentLocation:CLLocation?

//outlets
@IBOutlet weak var whatTextField: UITextField!
@IBOutlet weak var whereTextField: UITextField!
@IBOutlet weak var whenTextField: UITextField!

@IBAction func onCreateEventClick(_ sender: Any) {

    let event = CAEvent(eventId: "123777abc", eventName: whatTextField.text, location: currentLocation)
    event.save { (error) in
        //handle event error
        print(error)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
        CLLocationManager.authorizationStatus() ==  .authorizedAlways){
        determineCurrentLocation()
    }
}


func determineCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
        //locationManager.startUpdatingHeading()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations[0] as CLLocation

    // Call stopUpdatingLocation() to stop listening for location updates,
    // other wise this function will be called every time when user location changes.
    // manager.stopUpdatingLocation()

    print("user latitude = \(currentLocation?.coordinate.latitude)")
    print("user longitude = \(currentLocation?.coordinate.longitude)")
}

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

И сначала я смог увидеть местоположение (например, не ноль). Теперь, однако, это ноль каждый раз. Я попытался изменить местоположение моего симулятора, и я подтвердил, что приложение в моем симуляторе разделяет местоположение. Я также добавил вызов к startUpdatingLocation(), добавил делегата didUpdateLocations и заметил, что didUpdateLocationsAny не вызывается. Есть еще идеи? Спасибо!

Ответы [ 2 ]

0 голосов
/ 03 сентября 2018

Вы вызываете метод locationManager startUpdatingLocation ()? Лучшее место для начала обновления местоположения - метод делегирования locationManager:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch(CLLocationManager.authorizationStatus()) {
    case .authorizedAlways, .authorizedWhenInUse:
        locationManager.startUpdatingLocation()
    case .denied, .notDetermined, .restricted:
        locationManager.stopUpdatingLocation()
    }
}
0 голосов
/ 03 сентября 2018

Местоположение обычно недоступно сразу после его запроса, после того, как вы установите свой объект в качестве делегата, вы должны реализовать func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) и установить currentLocation в последний элемент этого массива.

Этот метод будет вызываться при каждом получении или изменении местоположения.

...