locationManager.location始终为零

时间:2018-09-03 02:23:05

标签: ios swift cllocation

我实质上已经从互联网上取消了此代码:

//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 :(得分:3)

您是否调用locationManager的方法startUpdatingLocation()?开始更新位置的最佳位置是locationManager的委托方法:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch(CLLocationManager.authorizationStatus()) {
    case .authorizedAlways, .authorizedWhenInUse:
        locationManager.startUpdatingLocation()
    case .denied, .notDetermined, .restricted:
        locationManager.stopUpdatingLocation()
    }
}

答案 1 :(得分:1)

通常在请求位置后,该位置通常不可用,一旦将对象设置为委托,就应实现func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])并将currentLocation设置为该数组的最后一个元素。

只要获取或更改位置,就会调用该方法。