【问题标题】:User's latitude and longitude isn't passed to new view controller用户的纬度和经度没有传递给新的视图控制器
【发布时间】:2016-04-15 17:28:26
【问题描述】:

我有一个使用 CLLocationManager 获取用户当前纬度/经度的按钮,我试图将纬度/经度都传递到新的视图控制器中。获取纬度/经度有效,但是当我尝试将数据传递到我的新视图控制器时,它没有被传递。

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
    }
}

有什么帮助吗?


编辑:

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
    }
}

【问题讨论】:

    标签: swift cllocationmanager uistoryboardsegue


    【解决方案1】:

    原因是获取用户位置是异步的。这意味着您需要在位置可用时推送新的视图控制器(例如在didUpdateLocations 中)。或者尝试更早地获取用户位置。

    【讨论】:

      【解决方案2】:

      CLLocationManager 类中的 locationManager.startUpdatingLocation() 不是即时的,我相信。因此,按照您的设置方式,您希望它在调用getCurrentLocation()时立即保存纬度和经度值

      这摘自 Apple 在 CLLocationManager 上的文档

      调用它会导致位置管理器获取位置修复(可能需要几秒钟)并使用结果调用委托的 locationManager:didUpdateLocations: 方法。

      我建议在didUpdateLocations 方法中放置一个performSegueWithIdentifier,这样我们就知道纬度和经度已经设置好了。此外,如果您只需要应用程序中某些点的纬度和经度,那么我建议使用CLLocationManagerrequestLocation 方法,它会更新一次位置,而不是不断获取地图应用程序所需的位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多