gpt4 book ai didi

swift - Getlocation 函数无法正确查找位置

转载 作者:行者123 更新时间:2023-11-30 10:15:51 25 4
gpt4 key购买 nike

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

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

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

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

}

最佳答案

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

此处的实际示例代码:https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch22p773location/ch35p1032location/ViewController.swift

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

关于swift - Getlocation 函数无法正确查找位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com