Badr Bujbara
Badr Bujbara

Reputation: 8701

Firebase iOS Swift: Updating TableView After Removing A Child

I have a tableview that shows children of a reference. How can I update the tableview when a child is removed? The child can be removed from other devices and I want the tableview updates automatically. I know there is observe .childRemoved but not quit sure how to use it to update the tableview.

Upvotes: 0

Views: 679

Answers (2)

Tizer1000
Tizer1000

Reputation: 934

By using: self.tableView.reloadData()

e.g. From an old project where I was playing with a sync'd list.

self.ref.child("familys").child(currentUserData.family).child("list").observe(.value, with: { (DataSnapshot) in

        if DataSnapshot.hasChildren() == false{
            print("No list")
        }

        else{
            self.list = DataSnapshot.value as! [String]
        }
        self.tableView.reloadData()
}

Everytime something below the level of "shoppinglist" updates, this observe block of code is called. self.tableView.reloadData() recalls all the functions such as

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return(list.count)  
}

Hope this helps.

Upvotes: 1

Badr Bujbara
Badr Bujbara

Reputation: 8701

I used observe childRemoved. Then in the block, I emptied the array, reloaded the tableview, and called ref.observe .childAdded again.

ref.observe(.childRemoved, with: {(removedData) in 
            array.removeAll()
            tableView.reloadData()
            fetchUserRequests()
        })

Upvotes: 2

Related Questions