我正在尝试在启动时立即获取用户位置,为此,我实现了一个全局变量userLocation
,它将在AppDelegate的didFinishLaunchingWithOptions
函数中得到更新。我已经像这样实现了位置管理器:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
var locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()
}
return true
}
和扩展名:
extension AppDelegate: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
usersLocation = locations.last!
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
userLocation永远不会更新,我在userLocation = locations.last!
行放置了一个断点,它永远不会到达。
感谢您的任何建议
答案 0 :(得分:1)
我认为你也应该保留locationManager
变量。
var locationManager: CLLocationManager!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()
}
return true
}