swift 3 计算到当前位置的距离并将结果从最近到最远排序

swift 3 Calculate distance to current location and sort result from closet to furthest

我正在尝试计算从事件到我当前位置的距离,对结果进行排序并将其填充到表格视图中。我不断收到可选的展开值距离为零的错误。

     private func observeEvents() {
    refHandle = ref.observe(.childAdded, with: { (snapshot) -> Void in
        let eventDetails = snapshot.value as! Dictionary<String, AnyObject>
        let eventID = snapshot.key
        let location = eventDetails["location"] as! String!

        //calculating distance
        self.forwardGeocoding(address: location!)
        let distance = self.eventLocation?.distance(from: self.currentLocation!) as Double!
        //end calculating

        let dateTime = eventDetails["dateTime"] as! String!
        let addedByUser = eventDetails["addedByUser"] as! String!
        let attending = eventDetails["attendance"] as! String!
        if let name = eventDetails["eventName"] as! String! , name.characters.count > 0
        {

            self.events.append(Events(id:eventID, name: name, location: location!, dateTime: dateTime!, addedByUser: addedByUser!, attending: attending! , distance: distance!))
            self.events.sort(by: { [=11=].distance < .distance})

            self.tableView.reloadData()
        } else {
            print("Error ! Can't load events from database")
        }
    })
} //load events data to uitableview

我创建了一个函数 return 来自地址

的 CLLocation
      func forwardGeocoding(address: String) {
    CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
        if error != nil {
            print(error!)
            return
        }
        if (placemarks?.count)! > 0 {
            let placemark = placemarks?[0]
            self.eventLocation = placemark?.location
        }
    })
}

我终于找到了答案。问题是距离函数在那里被异步调用,因为结果总是为零。我为地址字符串中的 return 纬度和经度创建了 forwardGeocoding 函数的完成处理程序,并在嵌套的 firebase 侦听器中调用结果。这是代码,我希望如果有人 运行 遇到与我类似的问题会发现它有用。

  //Get lat and long

func getCoordinates(address: String, completionHandler: @escaping (_ lat: CLLocationDegrees?, _ long: CLLocationDegrees?, _ error: Error?) -> ()) -> Void {

    var _:CLLocationDegrees
    var _:CLLocationDegrees
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { (placemarks: [CLPlacemark]!, error: Error!) in

        if error != nil {

            print("Geocode failed with error: \(error.localizedDescription)")

        } else if placemarks.count > 0 {

            let placemark = placemarks[0] as CLPlacemark
            let location = placemark.location

            let lat = location?.coordinate.latitude
            let long = location?.coordinate.longitude

            completionHandler(lat, long, nil)
        }
    }
}

firebase 侦听器中的嵌套调用

    refHandle = ref.observe(.childAdded, with: { (snapshot) -> Void in
    let location = event["address"] as! String          
    self.getCoordinates(address: location!) { lat, long, error in
            if error != nil {
                print("Error")
            } else {
                self.latitude = lat
                self.longitude = long
                let distance = CLLocation(latitude: self.latitude!,longitude: self.longitude!).distance(from: self.currentLocation!)

                if let name = eventDetails["eventName"] as! String! , name.characters.count > 0
                {

                    self.events.append(Events(id:eventID, name: name, location: location!, dateTime: dateTime!, addedByUser: addedByUser!, attending: attending!, distance: distance))

                    self.events.sort(by: { [=11=].distance < .distance})

                    self.tableView.reloadData()
                } else {
                    print("Error ! Can't load events from database")
                }

            }
        }
    })