Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Last active August 22, 2017 20:17
Show Gist options
  • Save michaelevensen/e62b861bc6ef4c9f5d2d4fa92b937064 to your computer and use it in GitHub Desktop.
Save michaelevensen/e62b861bc6ef4c9f5d2d4fa92b937064 to your computer and use it in GitHub Desktop.
Correct Ordering Descending Firebase
/*
* Custom Ordering Field: Descending
* - Trust me, this is the simplest way to do this with Firebase. 🤘
*/
imageObj["order"] = -image.uploadedAt.timeIntervalSince1970
/* */
FirebaseDatabaseReference.photos
.child(eventKey)
.queryOrdered(byChild: "order")
.observe(.childAdded, with: { snapshot in
do {
let image = try Image(snapshot: snapshot)
// Note to self: Need to do this also to maintain descending ordering after first init from .queryOrdered(byChild: "order").
// Now you're thinking why not just do self.images.insert(image, at: 0) right? Well that fucks up initial ordering so just don't. Trust me.
self.images.append(image)
self.images.sort(by: {$0.uploadedAt > $1.uploadedAt})
// Update UI
self.imagesCollectionView.insertItems(at: [IndexPath(row: self.images.count - 1, section: 0)])
self.imagesCollectionView.scrollToItem(at: IndexPath.zero, at: .right, animated: true)
// Important! Reload Data off the main queue.
DispatchQueue.main.async(execute: self.imagesCollectionView.reloadData)
}
catch let error {
print("Database error at \(FirebaseDatabaseReference.photos.child(eventKey)): \(error.localizedDescription)")
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment