skip to Main Content

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


  1. This is the function that fetches data if you have pushed new data to your dataBase

    extension YourViewController: NSFetchedResultsControllerDelegate {
        
        func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
            
            //Fetch Your Data
    
        }
        
    }
    
    Login or Signup to reply.
  2. 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 
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search