locationManager.location始终为零

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

我基本上从互联网上解除了这个代码:

//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。还有其他想法吗?谢谢!

ios swift cllocation
2个回答
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
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.