2017-08-24 133 views
0

我想按距离排序我的数组。我已经拥有了一切能够抓住距离的东西,但不确定如何从最接近最远的用户位置进行排序。我已经使用MKMapItem的下面的代码,但不确定如何应用到我当前的数组。Swift Firebase按距离排序

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!) 
        }) 
       } 

火力地堡呼叫

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) 
    } 
} 
+0

所以你要对我们进行排序根据distanceLabelText ersArray? – 3stud1ant3

+0

是的,这将是完美的 –

+0

你想在哪里排序usersArray,为什么? – 3stud1ant3

回答

1

首先要在你的代码中的这些变化

singleChildDictionary["distanceInMiles"] = distanceInMiles 

然后你就可以像这样对它进行排序:

self.usersArray = self.usersArray.sorted { 
     !($0["distanceInMiles"] as! Double > $1["distanceInMiles"] as! Double) 
} 
+0

我会在哪里申报呢?在通话中? –

+0

我猜测第二部分可能是一个函数,可以放在文件的任何位置? –

+0

@LukasBimba添加第一行之后singleChildDictionary [“distanceLabelText”] = distanceLabelText如AnyObject然后self.usersArray.append(singleChildDictionary作为NSDictionary的)后添加第二部分的xcode – 3stud1ant3