Swift Firebase observe with .childAdded retrieving duplicate data -
i have uicollectionviewcontroller
acts feed retrieves , displays data firebase database. it's window's root view controller, exists. issue every time controller appears, of children observed node added collection view. fine initially, when leave controller , return, of same data gets appended, creating duplicates. here pseudo-code, representing interaction firebase:
class viewcontroller: uiviewcontroller { var children_query: databasequery! override func viewdidload() { super.viewdidload() self.children_query = database.database().reference().child("children").queryordered(bychild: "timestamp").querystarting(atvalue: date().timeintervalsince1970) } override func viewwillappear(_ animated: bool) { super.viewwillappear(animated) self.observeaddedchildren() } override func viewwilldisappear(_ animated: bool) { super.viewwilldisappear(animated) self.children_query.removeallobservers() } func observeaddedchildren() { self.children_query.observe(.childadded, with: { snapshot in print(snapshot.value) }) } }
in pseudo-code, instead of dealing ui, print snapshot
, point remains. of children printed each time controller appears. how can retrieve only data hasn't been retrieved? thanks.
i haven't used firebase, when pass block observe
function, there's nothing suggest observation stops when view disappears.
so wonder if calling observe
multiple times problem. have tried calling observe
once, in viewdidload?
alternatively, have property record whether observation has been started:
var observing: bool = false func observeaddedchildren() { if observing { return false } self.children_query.observe(.childadded, with: { snapshot in print(snapshot.value) }) observing = true }
edit: here's couple more ways, because you're presumably adding snapshot
items array or other collection, uicollectionviewdatasource
reading stuff array.
so either:
- empty array inside
viewwillappear
, callself.collectionview.reloaddata()
, or - if
snapshot
object has unique identifier property, put array, , observe block can ignore items it's seen before
like this:
var snapshotids : [string] = array<string>() func observeaddedchildren() { self.children_query.observe(.childadded, with: { snapshot in if !snapshotids.contains(snapshot.uniqueid) { print(snapshot.value) snapshotids.append(snapshot.uniqueid) } }) }
Comments
Post a Comment