Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

swift - Read data to table view from firebase in real time

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)
                
            }
        })
question from:https://stackoverflow.com/questions/66060587/read-data-to-table-view-from-firebase-in-real-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...