Swift 用户';s纬度和经度为';t传递给新的视图控制器
我有一个使用CLLocationManager获取用户当前纬度/经度的按钮,我正在尝试将纬度/经度传递到一个新的视图控制器。获取纬度/经度是可行的,但当我试图将数据传递到新的视图控制器时,却无法传递Swift 用户';s纬度和经度为';t传递给新的视图控制器,swift,cllocationmanager,uistoryboardsegue,Swift,Cllocationmanager,Uistoryboardsegue,我有一个使用CLLocationManager获取用户当前纬度/经度的按钮,我正在尝试将纬度/经度传递到一个新的视图控制器。获取纬度/经度是可行的,但当我试图将数据传递到新的视图控制器时,却无法传递 func getCurrentLocation() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManage
func getCurrentLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation: CLLocation = locations[0]
self.userLongtitude = currentLocation.coordinate.longitude
self.userLatitude = currentLocation.coordinate.latitude
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationVC = segue.destinationViewController as! ListOfEventsTableViewController
if segue.identifier == "useCurrentLocation" {
getCurrentLocation()
destinationVC.userCurrentLat = self.userLatitude
destinationVC.userCurrentLong = self.userLongtitude
}
}
有什么帮助吗
编辑:
原因是获取用户位置是异步的。这意味着您需要在位置可用时推送新的视图控制器(例如在
didUpdateLocations
中)。或者尝试更早地获取用户位置。我相信CLLocationManager
类中的locationManager.startUpdatingLocation()
不是即时的。因此,按照您的设置方式,当您调用getCurrentLocation()
这是从苹果公司关于CLLocationManager
调用它会导致位置管理器获得位置修复(可能需要几秒钟),并使用结果调用代理的locationManager:didUpdateLocations:方法
我建议在didUpdateLocations
方法中放置一个performsguewithidentifier
,这样我们就知道纬度和经度已经设置好了。此外,如果你只需要应用程序中某些点的纬度和经度,那么我建议使用CLLocationManager
requestLocation
方法更新一次位置,而不是不断获取地图应用程序所需的位置
func getCurrentLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
self.userLongtitude = location.coordinate.longitude
self.userLatitude = location.coordinate.latitude
self.performSegueWithIdentifier("useCurrentLocation", sender: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationVC = segue.destinationViewController as! ListOfEventsTableViewController
if segue.identifier == "useCurrentLocation" {
destinationVC.userCurrentLat = self.userLatitude
destinationVC.userCurrentLong = self.userLongtitude
}
}