1
votes

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()
}
1
Can you show code for View Controller 2? - dst3p
Firebase work asynchronously, so instead of calling data in viewWillAppear use a delegate in viewController2 for tableView of viewController1 to reload data. - Basir Alam

1 Answers

1
votes

You shouldn't use observeSingleEvent since you want the code to be executed every time the firebase database changes. So, change it:

func fetchItems() {
ref.child("items").observe(.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()
})

}

This will create a listener. Also, since you didn't create an observer before, you didn't have to use removeAllObservers(). Now that you have one it's correct to use it. Hope it helps!