简体   繁体   中英

Count Firebase Database children and display

I programmed a tableView which displays posts from my Firebase database. In my sidebar (before the user gets to the tableView) I added a label which should display the number of Posts displayed in the tableView, so the user knows if there's something inside. So my question is: How can I track the number of children, stored under my topic "offers" and display them in my counterLbl?

var ref: DatabaseReference!
ref = Database.database().reference()

ref.child("offers").observe(.childAdded, with: { snapshot in

counterLbl.text = ...
}

If you're listening for .childAdded already, you can just keep a counter and increment that:

var nodeCount: Int = 0

ref.child("offers").observe(.childAdded, with: { snapshot in
    nodeCount = nodeCount + 1
    counterLbl.text = String(nodeCount)
}

If your use-case also makes it possible that nodes are removed from the database, you should also listen for .childRemoved to decrement the counter:

ref.child("offers").observe(.childRemoved, with: { snapshot in
    nodeCount = nodeCount - 1
    counterLbl.text = String(nodeCount)
}

More advanced scenario

Note that this approach requires that you download all nodes that you want to count. This should work fine in your current scenario, since you're downloading all offers anyway. But as you get more data, you might want to only read/display a subset of the offers, and in that case the code above would only count the nodes in that subset.

If you still want the count of all offers in that case, the common approach is to keep a separate counter value in the database, that you update every time you add/remove an offer. For more on this, see:

Step 1. Create a class with the Values you want to store

class ListModel: NSObject {
    var UID:String?
    var Name:String?
    var Email:String?
}

Step 2. In Your ViewController add the below code

var ListArr = [ListModel]()


let ref = Database.database().reference().child("offers")
ref.observe(.childAdded, with: { (snapshot) in
    print(snapshot)
    guard let dictionary = snapshot.value as? [String : AnyObject] else {
       return
   }
   let Obj = ListModel()
   Obj.UID = snapshot.key
   Obj.Name = dictionary["name"] as? String
   Obj.Email = dictionary["email"] as? String

   self.ListArr.append(Obj)
   self.myTableView.delegate = self
   self.myTableView.dataSource = self
   self.myTableView.reloadData()

}, withCancel: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM