无法访问swift中的用户坐标

时间:2018-01-24 22:44:39

标签: swift mapkit

我可以获取坐标,但我不能在代码中的任何其他地方使用它们。这是我到目前为止所做的,注意:我已经省略了我要求用户权限等的代码,但这都是有效的

let manager = CLLocationManager()
var latitude: Double? // 
var longitude: Double?


 override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

    }

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    longitude = location.coordinate.longitude // This correctly assigns the longitude
    latitude = location.coordinate.latitude   // This works too
    manager.stopUpdatingLocation()
}


func greatSphericalDistance(lat1: Double, long1: Double, lat2: Double, long2: Double)
{
  // Code to calculate distance between two coordinates
}

// This is the function I want to use my latitude and longitude variables in
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell

    let item: Locations = feedItems[indexPath.row] as! Locations
    // Get references to labels of cell
    cell.eventNameLabel.text = item.title

    // BELOW IS WHERE latitude AND longitude ARE USED
    cell.distanceLabel.text = "\(greatSphericalDistance(long1: longitude!, lat1: latitude!, long2: item.coordinate.longitude, lat2: item.coordinate.latitude))"

但是,当然,如果我尝试在上述函数之外访问经度和纬度,它将无法工作,因为它们仍然是零。知道我怎么能做到这一点?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

正如杰伊所说,你需要在你获得坐标后重新加载桌面视图。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    longitude = location.coordinate.longitude // This correctly assigns the longitude
    latitude = location.coordinate.latitude   // This works too
    manager.stopUpdatingLocation()
    self.tableView.reloadData() // <- Add this line
}