baken
baken

Reputation: 25

Swift and Firebase Real-Time-Database: How do I get the number of objects?

I just started learning Swift and I am trying to display fruits, which I added into my Real-Time-Firebase, on a list. I am stuck getting the number of fruits out of my Database. Here is my Database in JSON:

  "fruits" : {
    "apple" : {
      "price" : 4,
      "rate" : 6
    },
    "banana" : {
      "price" : 2,
      "rate" : 5
    },
    "orange" : {
      "price" : 10,
      "rate" : 9
    }
  }

I know how to read and write Data but don't know how to get the number of Fruits in Swift. Please help me. Thanks

Upvotes: 2

Views: 333

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598797

To determine the number of child nodes in a snapshot, use its DataSnapshot.childrenCount property. So something like:

ref = Database.database().reference()
ref.child("fruits").observe(.value) { snapshot in
  print(snapshot.childrenCount)
}

Note that this loads all data under fruits from the database to your app, and performs the count inside your application. There is no operator to perform the count of the server and only get that result.

Upvotes: 2

Related Questions