user10590916
user10590916

Reputation:

Swift load firebase database data when there is a change in data

I have a tableview set up that is fetching my firebase database info like so below. How do I set up a listener to look for any new database changes? At the moment, while looking at my tableview, I can add a new item to the database but won't see the change on my tableview until i reload that view again.

var markets: [loadMyData] = []
    var marketSelectedText = ""
    var myKey = [Any]()


    override func viewDidLoad() {
        super.viewDidLoad()


        ref.child("Markets").observeSingleEvent(of: .value, with: { (snapshot) in

            guard snapshot.exists() else
            {
                print("Null Markets")
                return
            }

            let allMarkets = (snapshot.value as! NSMutableDictionary).allKeys
            self.myKey = allMarkets
            self.tableView.reloadData()
            print(self.myKey, " This is the printing of my key")
        })

        ref.child("Markets").observe(.value, with: { snapshot in
            print(snapshot.value as Any, " ref.observe")
            self.tableView.reloadData()
        })



    }

Upvotes: 1

Views: 1500

Answers (2)

Zeeshan Ahmed
Zeeshan Ahmed

Reputation: 864

Firebase is providing listeners to observe database changes, kindly check the firebase documentation https://firebase.google.com/docs/database/ios/lists-of-data

  • FIRDataEventTypeChildChanged this is the event for listening database changes

    commentsRef.observe(.childChanged , with: { (snapshot) in

    // here you will get the changed node value here in snapshot.value

    })

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Right now you're using:

ref.child("Markets").observeSingleEvent(of: .value,

This observes the current data under Markets and then stops observing.

If you want to get both the current data and any changes, use observe(DataEventType.value.

Upvotes: 1

Related Questions