【发布时间】:2017-11-18 12:33:50
【问题描述】:
请检查代码:
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()
...}
所以,在所有 viewDidLoad() 内容加载之前,我无法获得 manager.startUpdatingLocation() 函数的结果。
问题:是否有可能在所有其他功能运行之前获得坐标?如果是,请描述如何?
【问题讨论】:
-
您可以使用所有 LocationManager 逻辑定义一个单例类,并在您的 appDelegate 中初始化该类
-
@ReinierMelian 当然,这样做可能会有所改善。但是我们真的可以确定我们会在在第一个视图控制器出现之前得到我们的位置吗?在一般情况下,我不这么认为......
-
不。通常,您需要将这些其他功能移到您的
locationManager(_:didUpdateLocations)方法中。不过有一个想法:您可以从某种默认位置(或者可能是用户的最后一个位置)开始吗?如果是这样,您可以将其存储在UserDefaults中并将其拉出viewDidLoad以供最初使用的功能。然后,当实际位置信息返回时,您可以使用新数据进行适当的响应。
标签: ios swift uiviewcontroller cllocationmanager