【发布时间】:2018-06-22 22:46:21
【问题描述】:
我试图简单地获取用户的当前设备位置并将其存储在一个名为 userLoc 的全局变量中。我有这段代码可以调用 didUpdateLocation:
self.locationManager.requestLocation()
print("aaa ", self.userLoc)
并将 userLoc 设置为当前位置:
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
self.userLoc = location
}
}
userLoc 定义如下:
var userLoc: CLLocation?
但是当我运行应用程序并尝试打印 userLoc 时,它总是会打印:
aaa nil
Privacy - Location When In Use Usage Description 在 Info.plist 中设置。老实说,我不知道还能尝试什么。一段时间以来,我一直在努力解决这个问题。您可以提供的任何帮助将不胜感激。谢谢你。
【问题讨论】:
-
您的
print线路早在位置更新之前就已被调用。 -
更新位置通常需要多长时间?我是这么想的,但我也尝试输入
sleep几秒钟,看看它是否有时间更新。什么都没有 -
请使用
sleep,尤其是在主线程中。只需将您的print移动到您设置self.userLoc的行之后。并检查控制台是否有任何与缺少隐私设置相关的消息。并确保您已致电self.locationManager.requestWhenInUseAuthorization。有很多关于如何正确使用 CoreLocation 的示例和教程。 -
我总是最终使用位置。首先...不确定这是否重要。
-
当我按照您的建议进行操作时,会打印 userLoc,但是当我尝试引用 userLoc 时,它会崩溃,因为 userLoc 仍然为零。当我尝试
self.locationManager.requestWhenInUseAuthorization行时,我得到一个错误:Expression resolves to an unused function