How to get parent from child - swift

So let's say I found that a value in database matches value entered by user through query. How can I find the parent of that value?
Ex. Let's say I enter in 35 as the age. 35 is also found in the database so how do I get the parent of that value (0)? Underlined in the picture.
I saw some similar questions asked but I can't seem to find a right answer to my question. Additionally, most of them are in different language.
Here is what I got so far:
#IBAction func onDiagnose(_ sender: Any) {
let ref1 = Database.database().reference(fromURL: "https://agetest.firebaseio.com/")
let databaseRef = ref1.child("data")
databaseRef.queryOrdered(byChild: "age").queryEqual(toValue: Int(ageTextField.text!)).observeSingleEvent(of: .value, with: { (snapshot) in
// if there is data in the snapshot reject the registration else allow it
if (snapshot.value! is NSNull) {
print("NULL")
} else {
//print(snapshot.value)
//get parent
//snapshot.ref.parent?.key! as Any
}
}) { (error) in
print(error.localizedDescription)
}
}

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So you need to loop through the child nodes of the resulting snapshot to get at the individual results:
databaseRef.queryOrdered(byChild: "age").queryEqual(toValue: Int(ageTextField.text!)).observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
print(child.key)
}
}) { (error) in
print(error.localizedDescription)
}
Also see listening to value events for lists of data in the Firebase documentation.

Related

How to retrieve data's name in Firebase

I'm not sure if "data's name" is the correct way to call it but here is my problem:
I have a table like this
I want to create 2 arrays that contain the ID (0001, 0040) and the Date (13-9-2017).
Because IDs are generated automatically so I don't know how to query
What I've tried:
func retrievingPresciptionID(){
let userID = appDelegate.userIDFirebase
Database
.database()
.reference()
.child("UserInformation")
.child(userID)
.child("prescriptionID")
.observeSingleEvent(of: .value, with: {snapshot in
if snapshot.exists(){
for id in snapshot.children {
self.prescriptionID.append((id as AnyObject).key)
}
print(self.prescriptionID)
}else{
print("snapshot failed")
}
})
}
It printed snapshot failed
Assuming we get the dict for the prescriptionIDs..
for prescription in prescriptionIDs {
IDArray.append(prescription.key)
dateArray.append(prescription.value)
}
The problem is you are not getting your dict to create your two arrays. Find the node that is missing.

Firebase swift not retrieving all child values

I have a piece of code inside my Swift built iOS app, to retrieve all the nodes from a Firebase Realtime database. When I execute the code below I've noticed that it does not return all the child nodes.
When I query the particular nodes which are not being returned individually, at first the code returns 'nil' and then on a second attempt retrieves the nodes. (without doing any code changes in the process). Following this process, the node starts to show up in the results with the retrieve all nodes function.
Example 1: First returns nil, then on a second attempt returns the node. Which I can see from the console and definitely exists on the database.
ref?.child("transactions").child(email).child("14526452327").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
print(value)
print("!!****************!!")
// ...
}) { (error) in
print(error.localizedDescription)
}
The following is being used to retrieve all child values; at first this doesn't get all the nodes, however after running the code from Example 1 (twice) it starts to return the node in question.
ref?.child("transactions").child(email).observeSingleEvent(of: .value, with: { (snapshot) in
let childrenCount = snapshot.childrenCount
var counter : Int = 0
for trans in snapshot.children.allObjects as! [DataSnapshot]
{
counter = counter + 1
self.ref?.child("transactions").child(email).child(trans.key).observeSingleEvent(of: .value, with: { (snapshot2) in
I've also checked my Firebase query and data limits and I am nowhere near the threshold for the free account. Any help is greatly appreciated.
Try this:
func getData() {
// Making a reference
let transactionRef = Database.database().reference(withPath: "transactions")
transactionRef.observeSingleEvent(of: .value, with: { (snapshot) in
// Printing the child count
print("There are \(snapshot.childrenCount) children found")
// Checking if the reference has some values
if snapshot.childrenCount > 0 {
// Go through every child
for data in snapshot.children.allObjects as! [DataSnapshot] {
if let data = data.value as? [String: Any] {
// Retrieve the data per child
// Example
let name = data["name"] as? String
let age = data["age"] as? Int
// Print the values for each child or do whatever you want
print("Name: \(name)\nAge: \(age)")
}
}
}
})
}

having problems in adding more than 1 information in the same child firebase

I want to achieve this:
This is my current database. It only shows 1 information but it should be showing 3 messages:
// loading the info onto firebase database
let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
ref.child("workout").observeSingleEvent(of: .value, with: { (snapshot) in
print("Got Snapshot")
print(snapshot.childrenCount)
let chilidCount = snapshot.childrenCount
print(chilidCount)
let post:[String:String] = ["\(chilidCount + 1)": textField.text!]
print(post)
ref.child("workout").child(uid!).setValue(post)
})
self.tableView.reloadData()
This is my code so far. I tried looking at other previous question from StackOverflow and also looked at firebase documentation but could not find anything useful.
This is my tableview
Try making a dictionary of the values you want to upload to your FIR Database.
I assume you want to upload the values to your database in a "workout" folder, and in that upload values for each user. You should do the following:
let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
//Reference to the location where the messages get saved to
let userWorkoutRef = ref.child("workout").child(uid!)
userWorkoutRef.observeSingleEvent(of: .value, with: { (snapshot) in
// Get the number of messages
let messagesCount = snapshot.childrenCount
//Making a dictionary: the key is the current number of messages plus one, the value is the current text entered in the text field
let valueToUpload = ["\(messagesCount + 1)": textField.text!]
//Uploading the dictionary to the database
userWorkoutRef.updateChildValues(valueToUpload) { (err, ref) in
if err != nil {
print(err!.localizedDescription)
return
} else {
print("success uploading data to db!")
}
}
}

Query to count number followers swift 4

I'm trying to count the number of followers the user has from my firebase database but no success. The number of followers is returning any value. When a user follows another user it creates a node in firebase with the userID and a Int value of 1 as shown below.
fileprivate func countTrusting() {
guard let userId = self.user?.uid else { return }
guard let currentLoggedInUser = Auth.auth().currentUser?.uid else { return }
Database.database().reference().child("following").child(userId).queryOrderedByValue().queryEqual(toValue: 1).observe(DataEventType.value, with: { (snapshot) in
let count = String(snapshot.childrenCount)
self.trustedLabel.text = "\(count) \nFollowing"
}) { (error) in
print("There was an error getting the following count:", error)
}
}
My firebase database
If I understand the question, you want to have a count of the number of followers of a user. In that case, there's no need for a query as the only nodes that will exist are the users followers.
This code reads in the child followers nodes and prints the count.
let userFollowingRef = fbRootRef.child("following").child("some_user_uid")
userFollowingRef.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount)
})

How to check if a Firebase DB node value is true using swift?

I have the following Firebase DB structure (see pic) which is created when a user sends a compliment to another user.
The compliment is saved under compliments with an auto-generated id
The compliment.key is also saved under users-compliments, under senderID/receiverID/then the "complimentID":"boolean" pair to indicate if it is "active"
I wish to check if an "active" compliment exists before being allowed to send another one to the same user.
But the following query results in a null output even though there is a child node with a value of 1.
What am I doing wrong here?
Query:
REF_USERS_COMPLIMENTS.child(currentUid).child(forId).queryEqual(toValue: "1").observeSingleEvent(of: .value) { (snapshot) in
print("snap: \(snapshot.value)")
}
Console output:
snap: Optional(<null>)
When using queryEqual() you have to combine it with an queryOrderedBy. In your case it would be queryOrderedByValue() because you want to compare the value:
REF_USERS_COMPLIMENTS.child(currentUid).child(forId).queryOrderedByValue().queryEqual(toValue: "1").observeSingleEvent(of: .value) { (snapshot) in
print("snap: \(snapshot.value)")
}
More information about this can be found in the docs.
Try this:
REF_USERS_COMPLIMENTS.child(currentUid).child(forId).observeSingleEvent(of: .value) { (snapshot) in
print("snap: \(snapshot.value)")
if let _ = snapshot.value as? NSNull {
// do your thing
}
}