Reputation: 286
I want to create a function that will update my tableview whenever changes are made to the database.
Database.database().reference().child("users").child(uid).child("tasks").observeSingleEvent(of: .childAdded, with: { (snapshot) -> Void in
self.refreshData() // REFRESH for New Task Created
})
Database.database().reference().child("users").child(uid).child("tasks").observeSingleEvent(of: .childRemoved, with: { (snapshot) -> Void in
self.refreshData() // REFRESH for Task Deleted
})
Database.database().reference().child("users").child(uid).child("tasks").observeSingleEvent(of: .childChanged, with: { (snapshot) -> Void in
self.refreshData() // REFRESH for Task Edited
})
The above observers that I call in my viewDidLoad() don't catch most changes made and stop working completely shortly after the project runs. How can I fix this / is there a better, working observe function that can update labels if changed are made and update my tableview if rows are deleted?
Upvotes: 2
Views: 942
Reputation: 598728
Your code is using .observeSingleEvent(of:
, which (as its name implies) observes a single event of the type and then stops listening.
To keep listening for changes after the initial event, us observe
, so:
Database.database().reference().child("users").child(uid).child("tasks")
.observe( .childAdded, with: { (snapshot) -> Void in
...
Also see the Firebase documentation on listening for child events.
Upvotes: 4