0

so I'm working these days on a new project and I have a problem I can't solve, I hope someone can help me. I'm working on an iOS app, I'm storing all user data on Firebase Real time dB. My main goal is to get specific data from all users from particular positions, For example: Inside users, I have different UIDs of all the users in the dB. In each one of them, there is a username, I would like to retrieve the username of each user. In the future, I would like to store the location for each user under "Location". and then I would like to get all users that their location is "New-York". I'll be glad to get some ideas on how to figure it out! Thanks!

users

  XLS37UqjasdfkKiB
      username: "Donald"

  ei8d4eYDafjQXyZ
      username: "Barak"

  etcj0lbSX5Oasfj
      username: "Abdul"

  rglmlG6Rasdgk5j
      username: "Ron" 

1 Answers1

0

You can:

  1. Load all JSON from /Users.
  2. Loop over snapshot.children.
  3. Then get the value of each child's username property.

These are also the most common navigation tactics when it comes to Firebase Realtime Database, so you'll apply these to pretty much any read operation.

Something like this:

Database.database().reference().child("isers").observe(.value, with: { (snapshot) in
    if !snapshot.exists() {
         print("No users found")
    } else {
        for case let userSnapshot as DataSnapshot in snapshot.children {
            guard let dict = userSnapshot.value as? [String:Any] else {
                print("Error")
                return
            }
            let username = dict["username"] as? String
            print(username)
        }
    }
})

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hey Frank! thank you for your help! I'm sorry for the delay, I'm new in this site)), I implemented the code and I got 2 errors, Cannot find 'snapShot' in scope, same for Cannot find 'child' in scope. as well, why there is 2 types of snapshot? (snapShot and snapshot) can you clarify it? – Ron Tabachnik Apr 21 '21 at 16:54
  • Both were typos in the code. I fixed them above now. – Frank van Puffelen Apr 21 '21 at 17:12
  • It did the job! Thank you very much for your help! Can I ask additional question? how can I get the UID of each username? I've tried let uid = dict["uid"] as? String it doesn't work – Ron Tabachnik Apr 21 '21 at 23:21
  • Since you use the UID as the key of the nodes in the database, you can find them as `userSnapshot.key` inside the loop. – Frank van Puffelen Apr 21 '21 at 23:22
  • There is no operator to exclude a specific node from a query results, so you will have to filter that client-side. – Frank van Puffelen May 11 '21 at 13:23