Hello I am writing and retrieving data from firebase, after writing some data I need to close the app and reopen to see the data that added.
private let ref = Database.database().reference().child("categories")
viewDidLoad(){
self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
for user_child in (snapshot.children) {
let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: Any]
self.categoryId.append(user_snap.key)
}
})
2
Answers
This is the function that fetches data if you have pushed new data to your dataBase
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 inviewWillAppear
or some other function, instead ofviewDidLoad
.However, a better way is to use
observe
instead ofobserveSingleEvent
. This call can be made fromviewDidLoad
; your data will update in real time.Update
You can just switch to observe instead of observeSingleEvent.
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: