Getlocation函数无法正确找到位置 [英] Getlocation function not properly finding location

查看:180
本文介绍了Getlocation函数无法正确找到位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码应该返回设备的位置,以用于放置图钉。

My code is supposed to return the location of the device, for the purposes of placing a pin.

由于某些原因,多次调用它时,总是返回第一次调用时返回的值。

For some reason when it is called multiple times, it always returns the value returned the first time it was called.

代码中的打印返回第一个值。我可能忽略了一些显而易见的事情,但是我无法弄清楚是什么。

The prints in the code are returning the first value. I am probably overlooking something obvious, but I cannot figure out what.

func getLocation ()-> CLLocation! {
    locationManager.startUpdatingLocation()
    var x = locationManager.location
    println(x.coordinate.latitude)
    println(x.coordinate.longitude)
    return x

} 


推荐答案

问题这不是位置管理器的工作方式。 startUpdatingLocation()不会立即更改位置管理器的状态。相反,它在委托方法 locationManager:didUpdateLocations:回叫您。您必须设置一个委托并实现该委托方法,该委托方法必须是

The problem is that this is not how location manager works. startUpdatingLocation() does not immediately change the state of the location manager. Instead, it calls you back in a delegate method, locationManager:didUpdateLocations:. You must set a delegate and implement the delegate that delegate method, and that is where you receive your location.

此处的示例示例:< a href = https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch22p773location/ch35p1032location/ViewController.swift rel = nofollow> https://github.com/mattneub/编程-iOS-Book-Examples / blob / master / bk2ch22p773location / ch35p1032location / ViewController.swift

请注意,在该代码中,像您一样,我只想要一个位置。但是位置管理器将一直永久调用委托方法,直到我停止它为止,因此也必须停止它。但是,一次调用后,我无法立即停止它,因为在找到一个合适的位置之前,多次调用了委托方法。我一直在检查水平精度和经过的时间,当我得到足够好的位置或经过了太多的时间(也许我们在室内且无法获得好的精度)时,我停止了位置管理器。

Note that in that code, like you, I just want one location. But the location manager will keep calling the delegate method forever until I stop it, so I also have to stop it. However, I can't stop it immediately, after just one call, because the delegate method is called several times before I get a good location. I keep checking the horizontal accuracy and the time elapsed, and I stop the location manager when I get a good enough location or too much time has elapsed (perhaps we are indoors and cannot get good accuracy).

这篇关于Getlocation函数无法正确找到位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆