0

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 = ...
}
KENdi
  • 7,576
  • 2
  • 16
  • 31
Roman H
  • 251
  • 2
  • 10

2 Answers2

1

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This is the way I was completely sure to work. For some reason though nodeCount always equals 0... – Roman H Dec 20 '18 at 12:56
0

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)
Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25