I have two view controllers in my app: the first one displays items pulled from a Firebase database, and the second one lets users add and remove items from the database.
The problem is when a user adds an item in the second view controller and goes back to the first controller really fast. This will sometimes cause the Firebase database not save the item. As a consequence the first view controller won't to display the newly added items.
As far as the implantation goes, I fetch items in viewWillAppear and then remove the Firebase listener observer in viewDidDisappear. How can I fix this?
// first view controller code
var items = [Item]()
var ref: FIRDatabaseReference!
func fetchItems() {
ref.child("items").observeSingleEvent(of: .value, with: { (snapshot) in
self.items = []
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
if let dictionary = child.value as? [String: AnyObject] {
// Create item and append it to an items array
}
}
self.tableView.reloadData()
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.fetchItems()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
ref.removeAllObservers()
}