Sounds like you successfully present the data in your app, but you want your data in real time, so that your data view (tableview or whatever) is updated every time there’s a change in the database.
viewDidLoad
is called only when the viewController is created, that’s why your new data is not fetched until you restart the app.
You could keep the observeSingleEvent
but make the call in viewWillAppear
or some other function, instead of viewDidLoad
.
However, a better way is to use observe
instead of observeSingleEvent
. This call can be made from viewDidLoad
; your data will update in real time.
Update
You can just switch to observe instead of observeSingleEvent.
self.ref.observe(.value, with: { (snapshot) in
// Handle your data
})
Please refer to the docs for more context (https://firebase.google.com/docs/database/ios/read-and-write)
Update 2
This is how you avoid duplicates in your data array:
self.ref.observe(.value, with: { (snapshot) in
// Create an array to deal with the updated data
let updatedCategoryIds = [String]()
for user_child in (snapshot.children) {
let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: Any]
updatedCategoryIds.append(user_snap.key)
}
self.categoryIds = updatedCategoryIds
// Now that self.categoryIds holds real time data without duplicates you can present the data
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…