Reputation: 47
I have a Firebase Database whereby I'm trying to display 5 random users (with their name and email) by querying them by their age, on 5 different view controllers which are controlled by a UIPageViewController.
I have created the query code to display users by their age. The code is below:
func findoutinfo(){
let usersRef = Database.database().reference().child("Users")
let query = usersRef.queryOrdered(byChild: "Age").queryEqual(toValue: "21")
query.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let childSnap = child as! DataSnapshot
let dict = childSnap.value as! [String: Any]
let name = dict["Name"] as! String
let email = dict["email"] as! String
print(childSnap.key, name, email)
}
})
}
However, I haven't discovered a way of randomly picking 5 users and display their information on the various pages. Ensuring that all of them are different.
Upvotes: 0
Views: 32
Reputation: 2488
Unfortunately. Firebase doesn't provide you with a simple solution for picking random children. Depending on the use case you might have to go for different approaches.
If the list of Users isn't big, you can get all the users, put them in an array and then pick 5 of them randomly. Something like:
var selectedUsers = [[String: Any]]()
let qtyOfUsersToSelect = 5
var users = getUsersArrayFromFirebase() // Made up function where you should fetch the Users.
for i in 1...5 {
selectedUsers.append(users.remove(at: Int.random(0..<users.count)))
}
If you expect the database users to be big, then I would recommend you using Firebase functions and handling this on the backend.
Upvotes: 1