Firebase ios: get list of users by IDs - ios

Situation: I have a database with users, users can have friends and friends are linked to current user model as userID. So when I'm loading user data I'm receiving also a list of firebase IDs of his friends.
Question: Is there any way to receive firebase snapshot with all this users at once? Haven't found any suitable solution - .child() is linking directly with one object, queryOrderedByChild() and queryOrderedByValue() doesn't seem to make such requests.
Will be grateful for any advice.
Edit: Database structure:
{
"Users": {
"user_id_first" : {
"user_info" : {
"name": "name",
"age": "age"
},
"friends": {}
},
"user_id_second" : {
"user_info" : {
"name": "name",
"age": "age"
},
"friends": {}
},
"user_id_third" : {
"user_info" : {
"name": "name",
"age": "age"
},
"friends": {
"user_id_first" : true,
"user_id_second" : true
}
}
}
}
There are list of friend IDs, which are actually IDs of firebase users. All I need is to retrieve information for these users in one firebase snapshot (i.e. use one reference) without creating new reference for each friend like
myDBRef.child("Users").child("friend_id")

Use for loop to access all the friendsId :-
let parentRef = FIRDatabase.database().reference().child("Users")
parentRef.child(FIRAuth.auth()!.currentUser!.uid).child("friends").observeEventType(.Value, withBlock: {(snapshot) in
if snapshot.exists(){
if let friendsDictionary = snapshot.Value as! NSMutableDictionary{
for each in friendsDictionary as! [String : AnyObject]{
let friendsId = each.0 as! String
parentRef.child(friendId).observeEventType(.Value, withBlock: {(friendDictionary)
if let friendsInfo = friendDictionary.Value as! NSMutableDictionary{
//retrieve the info
}
})
}
}
}
})

Related

How to retrieve the User info?

I want to retrieve data uid in User table data but for a specific user , I have 2 users, and it seems that it grabs the 2 users uid but I want to grab with i speficy not both of them just one.
Thank You In advance
let specificDatabase = Database.database().reference()
specificDatabase.queryOrdered(byChild: "User/FirstName").queryEqual(toValue: "The user first name")
specificDatabase.observeSingleEvent(of: .value) { (snapShot: DataSnapshot) in
for child in snapShot.children {
print(snapShot.key)
}
}
Firebase Data Structure
"User" : {
"ez8sTAsqXTWfnuzizUXU69VS4qM2" : {
"FirstName" : "other",
"LastName" : "Martin",
"uid" : "ez8sTAsqXTWfnuzizUXU69VS4qM2"
},
}
"Data" : {
"ez8sTAsqXTWfnuzizUXU69VS4qM2" : {
"-Ll7jUYg6BxRAhWPLskg" : {
"Name" : "other Martin",
"Data1" : "data"
},
"-Ll7jW_elQIPTLESwDYD" : {
"Name" : "other Martin",
"Data1" : "data "
}
},
}
You're telling Firebase to order each child node of the root by its User/FirstName property and then filter on that. Since the child nodes of the root don't have a property at that path, the query returns no results.
Instead you want to order/filter each child node of /User by itsFirstName property, which you can do with:
let specificDatabase = Database.database().reference(withPath: "User")
specificDatabase.queryOrdered(byChild: "FirstName").queryEqual(toValue: "other")

Query object in child array

I am trying to use a query to retrieve data of student who are only 4 years old from my database but i cant figure out how to use Firebase to query the age (The array in each child).
{
"student" : {
"-Kv2RVDDsI-v6V7g_LBn" : [ {
"name" : "sam",
"age" : "6"
}, {
"name" : "tom",
"age" : "4"
}
],
"-hguyu-v6V7g_LBn" : [ {
"name" : "Tim",
"age" : "12"
}, {
"name" : "tom",
"age" : "4"
}
]
}
}
This is my code but it does no return anything.
ref.child("student").queryOrdered(byChild: "age").queryEqual(toValue: 4).observe(.childAdded, with: { (snapshot) in
let value = snapshot.value
print(value)
}) { (error) in
print(error.localizedDescription)
}
However, if i remove the queryOrdered(byChild: "age") it works.
Thanks.
You are referencing "Student" when actually your JSON database format child path name is "Students".
Also make sure that you are querying by key. Refer to the Firebase documentation to see how to query by key. I don't understand your structure though why you have 2 children per key.
Why not have a new key for each child?

Adding multiple children to Firebase database with Swift

I am trying to create multiple children inside a child. I can currently create this inside my recipe:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
}
}
}
}
Using:
let recipe: [String : Any] = ["name" : self.recipe.name,
"ID" : self.recipe.key]
The class of the recipe looks like this:
class Recipe {
var name: String!
var key: String
init(from snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: Any]
self.name = snapshotValue["name"] as! String
self.key = snapshot.key
}
}
But I now want to create another array of children which would be inside "method" and look something like this.
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": [
{
"step 1": "instruction 1"
},
{
"step 2": "instruction 2"
},
{
"step 3": "instruction 3"
}
]
}
}
}
}
Edit:
The recipe is updated this way
databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)
I have looked at Firebase How to update multiple children? which is written in javascript, but not sure how to implement it. Feel free to let me know if there are better questions or examples out there.
You can create multiple children inside of a node just as you have been doing with the "recipe" node. For example:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": {
"Step1":"instruction1",
"Step2":"instruction2",
"Step3":"instruction3"
}
}
}
}
This is better practice as you can look up each step by key. Although, as Firebase Database keys are strings ordered lexicographically, it would be better practice to use .childByAutoId() for each step, to ensure all the steps come in order and are unique. I'll just keep using "stepn" for this example though.
If you needed further information inside each step, just make one of the step keys a parent node again:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": {
"Step1": {
"SpatulaRequired" : true,
"Temp" : 400
}
}
}
}
}
This can be achieved by by calling .set() on a Dictionary of Dictionaries. For example:
let dict: [String:AnyObject] = ["Method":
["Step1":
["SpatulaRequired":true,
"temp":400],
["Ste‌​p2":
["SpatulaRequire‌​d":false,
"temp":500]‌​
]]
myDatabaseReference.set(dict)

Nested Key Query in Firebase?

Firebase Data Structure
{
"books": {
"-KaKjMMw-WQltqxrGEmj": {
"categories": {
"cat1": true,
"cat2": true
},
"author": "user1",
"title": "event1"
},
"-KaKjMMw-WQltqxrGEmk": {
"categories": {
"cat1": true,
"cat2": false
},
"author": "user1",
"title": "event2"
}
}
}
Query To find all books of a particular author
FNode.testNode.child("books")
.queryOrderedByChild("author")
.queryEqualToValue("user1")
.observeEventType(.Value) { (snapshot) in
print(snapshot)
}
Question:
I want to find all the books belonging to cat1. Couldn't figure out the query to do that.
After a lot of hit and trial, finally got my answer.
For the above structure. If you want to find all the books belonging to cat1 Here is the query for that:
FNode.testNode.child("books")
.queryOrderedByChild("categories/cat1").queryEqualToValue(true)
.observeEventType(.Value) { (snapshot) in
print(snapshot)
}
Note: FNode.testNode could be any node of type FIRDatabaseReference
To Firebase Team: Can you please include a sample of all possible firebase queries in data structures and put it alongside firebase docs. It's kind of hit-and-trial for us now.

Firebase fanout data to update specific fields remove other siblings fields

Each user has a conversation node, each time a new conversation has a new message I need to update both conversation nodes for the two user involved in the conversation, I want just to update the "lastMessage" and "tinestamp" fields here is my try:
let fanoutObject = [userPath : dataToUpdate,
otherUserPath : dataToUpdate]
K.FirebaseRef.root.updateChildValues(fanoutObject)
where the paths for each user is:
"/users/{userID}/conversations/{conversationID}"
and the dataToUpdate:
let dataToUpdate:[String:AnyObject] = ["timestamp" : message.timestamp,
"lastMessage": message.textBody]
Result:
The node conversations for each user is updated BUT other fields in the conversation node are removed !
the conversation node fro each user is:
"conversations" : {
"{conversationID}" : {
"lastMessage" : "your name ?",
"seen" : true,
"timestamp" : 1467849600000,
"with" : {
"country" : "US",
"firstName" : "John",
"profileImage" : "https://..."
}
}
}
note that the node conversations is inside a node user which is an element inside the root node users
and after update it's :
"conversations" : {
"{conversationID}" : {
"lastMessage" : "your name ?",
"timestamp" : 1467849600000,
}
}
but I was expecting just to update the two values and keep others ?
According to docs my code should works:
updateChildValues Update some of the keys for a defined path without
replacing all of the data.
It's a bit hard to parse your code, but most likely it's the behavior of updateChildValues() that is confusing you.
When you call updateChildValues(), the Firebase server will loop over the object that you pass in. For each path in there, it will replace the entire value at that path with the value from that you passed in.
So if your current JSON is:
{
"Users": {
"uidForUser1": {
"name": "iOSGeek",
"id": 2305342
},
"uidForUser2": {
"name": "Frank van Puffelen",
"id": 209103
}
}
And the update is (in JSON format, the lingua franca of the Firebase Database):
{
"users/uidForUser2/name": "puf",
"users/uidForUser1/name": "My actual name"
}
Your resultant JSON will be:
{
"Users": {
"uidForUser1": {
"name": "My actual name",
"id": 2305342
},
"uidForUser2": {
"name": "puf",
"id": 209103
}
}
But if you send the following update:
{
"users/uidForUser1": {
"name": "My actual name"
},
"users/uidForUser2": {
"name": "puf"
}
}
The resulting JSON will be:
{
"Users": {
"uidForUser1": {
"name": "My actual name"
},
"uidForUser2": {
"name": "puf"
}
}
Update
To update two fields in the same object, but leave the other fields unmodified:
{
"path/to/object/field1": "new value",
"path/to/object/field2": "new value2"
}
Alternatively, you can update the lastMessage and timeStamp data by replacing the old values by providing full path :
let lastMessagePath = "/users/{userID}/conversations/{conversationID}/lastMessage"
let lastTimeStampPath = "/users/{userID}/conversations/{conversationID}/timestamp"
K.FirebaseRef.child(lastMessagePath).setValue(message.timestamp)
K.FirebaseRef.child(lastTimeStampPath).setValue(message.textBody)

Resources