When I load the following Firebase Database data into my tableView, the data is sorted in ascending order by date. How can I order this by descending (show the newest post a
While I do recommend doing what was posted and creating a Class and doing it that way, I will give you another way to do sort it.
Since you already have it sorted in Ascending order from Firebase and you know the amount of records, you can do this:
guard let value = snapshot.children.allObjects as? [FIRDataSnapshot] else {
return
}
var valueSorted: [FIRDataSnapshot] = [FIRDataSnapshot]()
var i: Int = value.count
while i > 0 {
i = i - 1
valueSorted.append(value[i])
}
.reverse()
before using datamyRef.observe(.value) { (snapshot) in
guard var objects = snapshot.children.allObjects as? [DataSnapshot] else {
return
}
objects.reverse() //<========= HERE
//Now use your `objects`
...
}
When Firebase loads the data into your tableView data source array, call this:
yourDataArray.sortInPlace({$0.date > $1.date})
Swift 3 Version:
yourDataArray.sort({$0.date > $1.date})
Swift 4 Version:
yourDataArray.sort(by: {$0.date > $1.date})
Swift 5: Add reversed() to your objects after sorting by the required field. For example, let's assume you have a day of the month in the "day" field in FireStore. Something like this will do the trick (call loadData() function in viewDidLoad to see the output):
let db = Firestore.firestore()
func loadData() {
db.collection("FireStoreCollectionName").order(by: "day").getDocuments { (querySnapshot, error) in
if let e = error {
print("There was an issue retrieving data from Firestore, \(e)")
} else {
for document in querySnapshot!.documents.reversed() {
let data = document.data()
let fDay = data["day"] as! Int
print(fDay)
}
}
}
}