Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Last active January 28, 2020 22:54
Show Gist options
  • Save michaelevensen/67661c9fadfe4ba0828af800acffe179 to your computer and use it in GitHub Desktop.
Save michaelevensen/67661c9fadfe4ba0828af800acffe179 to your computer and use it in GitHub Desktop.
childAdded and childChanged UITableView handling with Firebase. Handles both live cell updates and new children.
// Database Reference
var ref: DatabaseReference!
var handle: UInt!
var updateHandler: UInt!
// Local store
var wishes = [Wish]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Observe new wishes
self.handle = self.ref.observe(.childAdded, with: { snapshot in
do {
let wish = try Wish(snapshot: snapshot)
// Replace with new data if exists
if let index = self.wishes.index(where: { $0.ref?.key == wish.ref?.key }) {
self.wishes[index] = wish
// Reload UITableViewCell
let indexPath = IndexPath(row: index, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
// Append (if not exists)
else if !self.wishes.contains(wish) {
self.wishes.append(wish)
// Order descending
self.wishes.sort(by: { $0.createdAt > $1.createdAt })
}
}
catch let error {
print(error)
}
self.tableView.reloadData()
})
// Observe wish updates
self.updateHandler = self.ref.observe(.childChanged, with: { snapshot in
do {
let wish = try Wish(snapshot: snapshot)
// Find wish and update
if let index = self.wishes.index(where: { $0.ref?.key == wish.ref?.key }) {
// Update wish
self.wishes[index] = wish
// Reload UITableViewCell
let indexPath = IndexPath(row: index, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
catch let error {
print(error)
}
self.tableView.reloadData()
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Remove observer
self.ref.removeObserver(withHandle: self.handle)
self.ref.removeObserver(withHandle: self.updateHandler)
}
@vishahemshub
Copy link

will you please show the structure of your data model Wish

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment