请检查代码:
let manager = CLLocationManager()
//Location manager to determine the current location
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
lat = location.coordinate.latitude
lon = location.coordinate.longitude
let currentLocation = CLLocation(latitude: lat!, longitude: lon!)
}
我在viewDidLoad()中还有更多功能:
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
//Here i want to get the result immediately, but...
manager.startUpdatingLocation()
parseJSONfunction()
anotherFunction()
anotherFunction2()
...}
因此,在manager.startUpdatingLocation()
个所有内容加载之前,我无法获得viewDidLoad()
函数的结果。
问题:在所有其他函数运行之前是否可以获取坐标?如果是,请描述如何?
答案 0 :(得分:2)
总之,没有。位置管理器是异步的。您要求它开始更新您的位置并启动GPS并尝试修复(它还使用手机信号塔,WiFi基站等)可能需要几秒钟(或更长时间)才能获得相当准确的信息读数。
当我编写位置感知应用时,我通常会启动位置管理器,并且在我的locationManager(_:didUpdateLocations:)
方法中,我会检查结果的水平准确性,只有在它处于最不合理的准确。这可能会花费更长的时间。
如果你加载一个viewController它是同步的。系统执行设置,这会导致触发各种框架调用,然后在视图加载后调用viewDidLoad,同步。如果在用户要求显示新的视图控制器时启动位置管理器,则在调用viewDidLoad时可能无法进行位置修复。
如果你加载你的应用程序,请让app delegate调用一个单例来开始位置更新,然后等待用户切换到你的另一个屏幕,然后在viewDidLoad中你有一个很好的机会向单身人士询问该位置获得良好的位置阅读,但即便如此,也不确定。