Last active
January 28, 2020 22:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
will you please show the structure of your data model Wish