本文介绍了Swift Firebase按距离排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按距离对数组进行排序.我已经将所有东西都连接起来以获取距离,但是不确定如何从用户位置最远到最远进行排序.我已将以下代码用于MKMapItem,但不确定如何应用于我的当前数组.
I am trying to sort my array by distance. I already have everything hooked up to grab the distance's but unsure how to sort from closest to furthest from the users location. I've used the below code for MKMapItem's yet unsure how to apply to my current array.
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) } } 推荐答案首先在您的代码中进行这些更改
First make these changes in your code
singleChildDictionary["distanceInMiles"] = distanceInMiles然后您可以按以下方式对其进行排序:
Then you can sort it like this:
self.usersArray = self.usersArray.sorted { !($0["distanceInMiles"] as! Double > $1["distanceInMiles"] as! Double) }更多推荐
Swift Firebase按距离排序
发布评论