【发布时间】:2018-02-02 15:17:19
【问题描述】:
我正在尝试按距离对数组进行排序。我已经将所有东西都连接起来以获取距离,但不确定如何从离用户位置最近到最远的位置进行排序。我已将以下代码用于 MKMapItem,但不确定如何应用于我当前的数组。
func sortMapItems() {
self.mapItems = self.mapItems.sorted(by: { (b, a) -> Bool in
return self.userLocation.location!.distance(from: a.placemark.location!) > self.userLocation.location!.distance(from: b.placemark.location!)
})
}
Firebase 调用
databaseRef.child("Businesses").queryOrdered(byChild: "businessName").observe(.childAdded, with: { (snapshot) in
let key = snapshot.key
if(key == self.loggedInUser?.uid) {
print("Same as logged in user, so don't show!")
} else {
if let locationValue = snapshot.value as? [String: AnyObject] {
let lat = Double(locationValue["businessLatitude"] as! String)
let long = Double(locationValue["businessLongitude"] as! String)
let businessLocation = CLLocation(latitude: lat!, longitude: long!)
let latitude = self.locationManager.location?.coordinate.latitude
let longitude = self.locationManager.location?.coordinate.longitude
let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)
let distanceInMeters : Double = userLocation.distance(from: businessLocation)
let distanceInMiles : Double = ((distanceInMeters.description as String).doubleValue * 0.00062137)
let distanceLabelText = "\(distanceInMiles.string(2)) miles away"
var singleChildDictionary = locationValue
singleChildDictionary["distanceLabelText"] = distanceLabelText as AnyObject
self.usersArray.append(singleChildDictionary as NSDictionary)
/*
func sortMapItems() {
self.mapItems = self.mapItems.sorted(by: { (b, a) -> Bool in
return self.userLocation.location!.distance(from: a.placemark.location!) > self.userLocation.location!.distance(from: b.placemark.location!)
})
}
*/
}
//insert the rows
self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
}
}) { (error) in
print(error.localizedDescription)
}
}
【问题讨论】:
-
那么你想根据distanceLabelText对usersArray进行排序吗?
-
是的,那将是完美的
-
你想在哪里对 usersArray 进行排序,为什么?
-
我在 firebase 调用中猜测,因为排序需要访问数组。或者也许之前只是通过调用一个函数来完成它?不知道什么是最有效的
-
我可以访问 userLocation 但尝试访问 usersArray 是问题
标签: ios arrays swift firebase tableview