Swift Firebase按距离排序

编程入门 行业动态 更新时间:2024-10-14 16:25:45
本文介绍了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按距离排序

本文发布于:2023-10-18 15:00:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:距离   Swift   Firebase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!