-1

I've been looking for so long for a way to count all of my users from my firebase database and then put the result in a for loop

The problem is that the counter stay at 0 even when I count..

here is a screenshot of my firebase database

here is what I tried

var count = 0
    FIRDatabase.database().reference().child("users").observe(.value, with: { (snapshot) in
        count = Int(childrenCount)
    })
    for i in 0...count {
        let card = ImageCard(frame: CGRect(x: 0, y: 0, width: self.view.frame.width - 60, height: self.view.frame.height * 0.6))
        cards.append(card)
    }

thank you !

  • 1
    Just a heads up, People will be Flagging this post because you've uploaded a screenshot of your code and you didn't just paste it. – Jake Mar 31 '18 at 14:44
  • Thank you for the tip I have just edit it :) – Daniel Ghrenassia Mar 31 '18 at 15:01
  • No loop is needed to get the count. It's available as a property on the [`snapshot.childrenCount`](https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DataSnapshot#childrencount). But it seems you are trying to loop over the users, which is easier to accomplish without a count. See https://stackoverflow.com/questions/27341888/iterate-over-snapshot-children-in-firebase – Frank van Puffelen Mar 31 '18 at 15:16
  • Another heads up. Please do not link to code or screenshots - links change and break and that invalidates the question as we then don't know what your Firebase looks like. To get your Firebase structure, use the Firebase console->Export JSON - you can then copy/paste it. See [Screenshots are Evil](http://idownvotedbecau.se/imageofcode) – Jay Apr 01 '18 at 11:53

1 Answers1

1

You'll do something like this.

Database.database().reference().child("users").observeSingleEvent(of: .value) { (snapshot) in 
    if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {                     
        print(snapshots.count)   
    } 
} 
Jake
  • 2,126
  • 1
  • 10
  • 23