How to get a child name in Firebase Realtime Database? [duplicate] - swift

This question already has answers here:
Firebase queryOrderedByChild() method not giving sorted data
(2 answers)
Retrieving Data using Firebase Swift
(1 answer)
Get the data from all children in firebase using swift
(2 answers)
Swift Firebase -How to get all the k/v when using queryOrdered(byChild: ).queryEqual(toValue: )
(1 answer)
Closed 3 months ago.
I have a Firebase Realtime Database and want to get the name of a child in the last part of a branch.
The database structure looks like this:
How do I get the "FD4936E20732A42E" and possible other child names of "friends"?
"FD4936E20732A42E" and other possible childs of "friends" are not string values I know before runtime.
I know how I would for example access the value for a specific part of the database. But in this case using snapshot.value and snapshot.key did not work.
I really appreciate any kind of help. I am really desperate.
Update - I tried this but the output is a FIRDataSnapshot and I need a String. A downcast is not working:
let ref = Database.database().reference().child("visitors").child("107C081B-4117-4E2F-8E39-BF896D366B30")
ref.child("friends").observeSingleEvent(of: .value) { snapshot in
for child in snapshot.children {
print(child)
}
}
The output I get:
Snap (FD4936E20732A42E) 1

Related

How to get all child data from firebase without knowing the path

My data structure looks like this:
I want to be able to access every users listings to make an array of all listings however I do not know every users ID or Listing ID so i can not do:
Database.database().reference.child("users").child(uid)...... because it is not for just one UID. if there a way to 'skip' over the .child(uid) and .child(listingID) when pulling from firebase?
If you want to retrieve all data for all users, you can attach your observer to the entire /users node. That will give you a snapshot of all data in the completion handler, and you can then loop over the children of that snapshot to get at each individual user.
Something like this:
ref.observeSingleEvent(of: .value) { snapshot in
for case let user as FIRDataSnapshot in snapshot.children {
print(user.childSnapshot(forPath: "email").value)
}
}
You can use similar loops to dive further down into the snapshot's data, and more calls to childSnapshot(forPath: to find specific properties.
Also see the answer I gave just an hour ago here and How do I loop all Firebase children at once in the same loop? and Looping in Firebase

Firebase Database: Retrieve node if child object has certain value

Im developing an app in iOS using Firebase. Was wondering if I can fetch data in the node, if a child object has certain value?
For instance, below is my database structure:
If i fetch data, it fetches all my data inside the LEREDrwBDM952MpVtUE node. However, my app solution requires me to display this node ONLY if monitored is false. If monitored is true, it will not display it.
My Code:
refChilds = Database.database().reference()
let userId: String = (Auth.auth().currentUser?.uid)!
//observing the data changes
refChilds.child("childId").child(userId).child("uid").queryOrdered(byChild: "monitored").queryEqual(toValue: "false").observe(DataEventType.value, with: { (snapshot) in
With the above code, Im note able to fetch anything. Is this the right way to fetch the data?
Edit:
Addition to my question, I was wondering how can I now update the childvalue of monitored from false to true? I'm having problems accessing the 2nd child node LEREDrwBDM952MpVtUE. My code creates a new node underneath TGEcwrz..
Here's my code.
refChild.child("childId").child(userId).updateChildValues(["monitored":monitored!])
You have a segment uid in your code that isn't in your JSON. From what I see the query should be:
refChilds.child("childId").child(userId).queryOrdered(byChild: "monitored").queryEqual(toValue: false).observe(DataEventType.value, with: { (snapshot) in

Querying an array in Firebase

I am sure this has been asked before but I am struggling to find a correct answer. I'm using Swift 3. Here's the problem:
I have a list of postID's in an array. I now want to query Firebase and if the postID exists, then retrieve the data and display it in my tableview.
What's the recommended way to do this ? Any code examples would be of great help. Ideally I would want to get all the posts and then update the table view in one shot. Thanks.
To be clear I am looking for the Firebase Query here that will help me achieve this.
Firebase structure
Try this
first create database reference till post
let mainRef = Database.database().reference().child("Posts")
Now suppose you have post id in myPostID variable
mainRef.child(myPostID).observeSingleEvent(of: .value) { (snapshot) in
print(snapshot)
if let value = snapshot.value {
// Value FOUND UPDATE YOUR TABLE HERE
} else {
// No ID found for this post
}
}
Hope it is helpful

How to set more than one value to a child in Firebase using Swift?

I am trying to make a money related app which shows the user their spendings as a project to get used to Firebase. So I stumbled upon this issue; I can't seem to figure out how to add more than one expense assigned to a user. Whenever I add a new expense, the existing value in Firebase gets reset to the new value but I want it to store both the new and the old value. How can I do this?
There's something called "autoID" if that helps. I'll link that in a few moments.
Edit: It's used here.
childByAutoId() is what you want for swift. See Updating Or Deleting specific data section in the Read and Write Data on iOS
let thisUserRef = ref.child("users").child(users uid)
let expenseRef = thisUserRef.child("expenses").childByAutoId()
let dict = ["expense_type": "travel", "expense_amt": "1.99"]
expenseRef.setValue(dict)
will results in
users
uid_0
-Y88jn90skda //<- the node key created with childByAutoId
expense_type: "travel"
expense_amt: "1.99"
the childByAutoId is super powerful and allows 'random' node keys to be generated that contain your child data.
See the answer to this question and this other question for some tips on data modeling and queries.

How to get the array of all keys from the dictionary in the existing order? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to sequentialy access a dictionary??
I have a dictionary , I want to reitrive all keys in an array with the same order which exist inside the dictionary . The documentation on "allKeys" method of NSDictionary says the order of returned objects in array is not defined . What can be done to get the keys in the same order as that of the dictionary .
Thanks a lot in advance !!
So the question you were pointed to summarises the issue nicely, but the solutions offered could be a little bit too complex for your needs (if you didn't want / have the time to write a sub-class or your own data structure).
The quick and dirty alternative is simple to have an array that contains all the keys you want to access in the order you want to access them in. You can then simply match this array back to your dictionary to pull out values in the correct order.