0

I'm using Firebase. In my app, I get a child value by passing in a bottleID and get the details for that value from the snapshot. I then assign the details to an object of MyCollection_Class and add it to an array. After getting every single bottle value, I want to sort that array using the created_at tag before reloading the table view. Please advise me on how to sort the array of objects by a specific instance variable.

let Collection = MyCollection_Class()
FireBaseConstants.AUCTIONS_REF.child(bottleID).observeSingleEvent(of: .value, with: { (snap) in
    if !(snap.value is NSNull) {
        Collection.id = bottle_dict["id"] as? String
        Collection.item_number = bottle_dict["item_number"] as? Int
        Collection.created_at = bottle_dict["created_at"] as? String
        if !(self.MyCollectionsIDArr.contains(Collection.id! as String)) {
             self.MyCollectionsArr.append(Collection)
             self.MyCollectionsIDArr.append(Collection.id!)
             // I want to sort the MyCollectionsArr using created_at here
             self.tbl_Latest.reloadData()
        }
    }
})
Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39
Mohanraj
  • 587
  • 4
  • 21
  • 1
    Can you show the sample value of `created_at` because it is of `String` type, so you need to show us the format of the date – Nirav D Apr 18 '17 at 12:34
  • 1
    Possible duplicate of [Swift how to sort array of custom objects by property value](http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – Pedro Castilho Apr 18 '17 at 12:39

1 Answers1

0

You can just retrieve the data already sorted from Firebase by using

queryOrderedByChild.

An example would be:

ref.child(bottleID).queryOrderedByChild("created_at").queryEqualToValue(0).observe  SingleEventOfType(.Value, withBlock: { snap in
    print("snap \(snap)")
    expectation.fulfill()
})
Reshad
  • 2,570
  • 8
  • 45
  • 86