如何从viewDidLoad调用“ didUpdateLocation”方法?

时间:2019-09-17 11:48:19

标签: ios swift4 cllocationmanager

我正在制作一个天气应用,该应用通过发送当前坐标来获取温度信息。所以我正在使用CLLocationManager。我还没有发出任何HTTP请求。我想在屏幕上看到“位置不可用”,但是它不起作用。

我正在遵循一个教程,并编写了完全相同的代码,但是在教程中它是有效的。在调试会话中,它不会跳转到didFailwithError或didUpdateLocations方法。我在我的程序中添加了所有必要的东西 info.plist和我手机的位置服务已打开。根据我的研究locationManager.startUpdatingLocation()应该自动调用 这些方法,但是当我运行我的应用程序时,UI上什么也没显示。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   print("you got the location")

}

//Write the didFailWithError method here:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
    cityLabel.text = "Location Unavaiable"
}

let locationManager = CLLocationManager ()
override func viewDidLoad() {
    super.viewDidLoad()

    //TODO:Set up the location manager here.
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

}

1 个答案:

答案 0 :(得分:1)

实际上是在您未获得用户许可之前,就过早更新位置。

在您请求许可后

locationManager.requestWhenInUseAuthorization()

代表方法将调用

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

}

现在该开始更新了。保护状态是个好主意,因为除非用户允许,否则您不希望开始更新。

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        guard status == .authorizedWhenInUse else { return }
        manager.startUpdatingLocation()

}

现在您将获得位置更新

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

        print(locations)

}