0
votes

I'm using Firebase as the database for my IOS app. I want to retrieve data of several users from the database.

Here is my database organization:

  • Users

    • UserID1
      • Location: value1
    • UserID2
      • location: Value2
  • ...

I want to retrieve the location data of all the users of the database.

The basic snapshot fonction

    ref.child("Users").child("").child("Location").observe(.value, with: {
        snapshot in

        for Location in snapshot.children {
            self.locationsArray.append((Location as AnyObject).key)
        }
        print(self.locationsArray)
    })

My question is: how can I retrieve all the Locations even if I don't specify (I can't) the userID that is the name of a child before? Thanks.

2

2 Answers

2
votes

Here's a code snippet that retrieves and prints the uid of each user and their location.

We can further refine our results with a .query

let usersRef = ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { (snapshot) in

    for snap in snapshot.children {
        let userSnap = snap as! FIRDataSnapshot
        let uid = userSnap.key //the uid of each user
        let userDict = userSnap.value as! [String:AnyObject] //child data
        let location = userDict["Location"] as! String
        print("key = \(uid) is at location = \(location)")
    } 
})
1
votes

It is not possible with Firebase to retrieve just the Location. There are a lot of option, but I see two that fits better in your case:

  1. Get everything from all users, and then manage in your code what you want;
  2. Create another dictionary only with users id and location.

The second option would be like:

  • UsersLocation
    • UserID1:Location1
    • UserID2:Location2

So every time you change your main array you need to change this too.