简体   繁体   English

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

[英]How to call “didUpdateLocation” method from viewDidLoad?

I am making a weather app which gets temperature info by sending current coordinates. 我正在制作一个天气应用,该应用通过发送当前坐标来获取温度信息。 So I am using CLLocationManager. 所以我正在使用CLLocationManager。 I haven't make any HTTP request yet. 我还没有发出任何HTTP请求。 I would like to see "Location Unavailable" on my screen but it is not working. 我想在屏幕上看到“位置不可用”,但是它不起作用。

I am following a tutorial and wrote exactly same code but in tutorial it is working. 我正在学习一个教程,并编写了完全相同的代码,但在教程中它正在工作。 In debug session, it doesn't jump to didFailwithError or didUpdateLocations methods.I added all necessary things in my info.plist and my phone's location services are open. 在调试会话中,它不会跳转到didFailwithError或didUpdateLocations方法。我在info.plist中添加了所有必需的东西,并且手机的定位服务处于打开状态。 According to my research locationManager.startUpdatingLocation() should call automatically these methods but when I run my app nothing appears on UI. 根据我的研究,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"
}

And

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()

} }

You are updating location too soon, in fact before you get the permission from user. 您实际上是在获得用户许可之前,太早更新位置。

After you ask for permission 在您请求许可后

locationManager.requestWhenInUseAuthorization()

Delegate method will call 委托方法将调用

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

}

Now its time to start updates. 现在该开始更新了。 Guarding the status is a good idea since you don't want to start updating unless user permits it. 保护状态是个好主意,因为除非用户允许,否则您不希望开始更新。

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

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

}

Now you'll get location updates 现在您将获得位置更新

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

        print(locations)

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM