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: