firebase snapshot key for children autoids - swift

I have the following structure :
DATA :
-kojasd- <----- child by autoid key name for folder
property:value
-kjofs- <----- child by aytoid key name for folder
property:value
how can I get the key value of the childbyautoid() in a snapshot.children loop ?
here s a bit of code to explain :
for items in snap.children {
let key = items.key as! String // DOESN T WORK
let value = items.value!!["property"] as! String
}
in this code, snap refers to DATA
I thought that it would be easy to get this key value, but I m stucked here since a long time, any help ?? :)
sincerely
Yann

For people who are using new Xcode 8 beta 3 and swift 3 , many notations have changed and something like the snippet below should give you the children values as String ; basically you would need to do another check and safely upward:
for childSnap in snapshot.children.allObjects {
let snap = childSnap as! FIRDataSnapshot
if let snapshotValue = snapshot.value as? NSDictionary, let snapVal = snapshotValue[snap.key] as? AnyObject {
print("val" , snapVal)
}
}

If let's say you have posts you can get it like this.
ref.child("posts").observeEventType(FIRDataEventType.Value, withBlock: { snapshot in
for childSnap in snapshot.children.allObjects {
let snap = childSnap as! FIRDataSnapshot
print(snap.key)
let property = snap.value!["property"] as! NSString
}
})
I know the awnser was already given but I wanted to give some more explanation.

I have spent a few moments with that too and although you said this doesn't work for you, I think this is how it should be done:
rootRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
for item in snapshot.children {
print(item.key)
}
})

ok, found a solution, I had to pass the snap into a new fdatasnapshot to get its key

Related

I want to get the child of my firebase (not the key) using swift

This is my firebase. I want to retrieve the names "anaesthesia", "musculoskeletal", "options" into an array and print it out. This is my swift code
ref?.child("mcqbase-159dc").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
self.categoriesArray.append(key)
print(self.categoriesArray)
}
}
})
It returns a blank in my terminal. Can anyone help me?
"anaesthesia", "musculoskeletal" and other your database table's names. You can change your structure to :
And your snapshot code must be :
Database.database().reference().child("names").observeSingleEvent(of: .value) { (snapshot) in
//Your code
}

Firebase - Order child value from low to high

I want to order my tableView with values from Firebase from low to high. This is what I got so far:
Database.database().reference().child("Bier").queryOrdered(byChild: "Voor_prijs_int").queryStarting(atValue: 0).queryEnding(atValue: 10000).observeSingleEvent(of: .value) { snapshot in
print("test")
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
print("test2")
for snap in snapshots {
print("test3")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
print("test4")
let key = snap.key
let bier = BierModel.transformbier(dict: postDict, key: key)
self.bier_model.insert(bier, at: 0)
}
}
}
}
When I run this code it seems that it get stuck by print("test2"), because it never print
test3
I am not sure why this is, because I have got this code from a other project that worked.
Here is my Firebase structure:
Thanks
This code will sort the data based on the smallest value of variable to the largest:
self.bier_model.sort { $0.variable < $1.variable }

Pull string value from firebase snapshot

I am a new Swift developer. I'm using Swift 4.2 and Xcode 10.1.
I'm trying to create an array of strings from a firebase snapshot. I am able to do this by setting up a struct model and using an initializer, but when I want to do it directly in the code without a separate struct it does not work. Here is my code:
// Get the likers
dbRef.child("likers").observeSingleEvent(of: .value) { snapshot in
// Declare an array to hold the Likers
var retrievedLikers = [String]()
// Loop through the retrieved likers and put into the array
for child in snapshot.children {
let snap = child as! DataSnapshot
let dict = snap.value as! [String:Any]
let likerId = dict["userId"] as? String ?? ""
print (likerId)
retrievedLikers.insert(likerId, at: 0)
}
likers = retrievedLikers
}
My firebase data model looks like this:
I have tried several methods. The code above is the most recent based on another SO suggestion.
The problem is that I can't create a dictionary with snap.value. Snap has the correct data. I am getting an error saying "Could not case value of type '__NSCFString' to 'NSDictionary'. But the snap is showing as a dictionary. Here's a screenshot:
Any help would be appreciated. I've tried for 3 hours to solve this.
You can try
let res = snapshot.value as! [String:String]
retrievedLikers = Array(res.values)
Here the crash snap.value is a String that can't be casted to [String:Any]
let dict = snap.value as! [String:Any]

Order tableviewcell by child timestamp

I tried with this code to sort my posts by timestamp it doesn't work, each time I launch the simulator the order of the cells is different, I suppose this isn't the way to do it, could somebody explain me where I am wrong...
I edited the code, now my problem is that the most recent posts are displayed at the bottom and I would like them to to be displayed at the top
self.user.removeAll()
for child in DataSnapshot.children.allObjects as! [DataSnapshot] {
print("Processing user \(child.key)")
let value = child.value as? NSDictionary
//if country == "UNITED STATES"{
if let uid = value?["userID"] as? String{
if uid != Auth.auth().currentUser!.uid {
//
let userToShow = User()
if let fullName = value?["username"] as? String , let imagePath = value?["photoURL"] as? String{
userToShow.username = fullName
userToShow.imagePath = imagePath
userToShow.userID = uid
self.user.append(userToShow)
}
}
}
}
As soon as you call DataSnapshot.value, you're converting the data in the snapshot into a dictionary. And the order if keys in that dictionary is not guaranteed.
To maintain the order of the elements as they come back from the database, you need to loop over DataSnapshot.children. See these questions for examples of how to do that:
Iterate over snapshot children in Firebase
post on the firebase-talk mailing list
For your code this would look something like:
ref.child("users").queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: { snapshot in
self.user.removeAll()
for child in snapshot.children.allObjects as [DataSnapshot] {
print("Processing user \(child.key)")
let value = child.value as? NSDictionary
if let uid = value["userID"] as? String {
...
}
}
self.tableview.reloadData()
})

Swift Firebase Get the parent value from children

I have this database structure:
I am trying to get the node value (for example: -KzjZJvEQRBlRG8m2RxO) if the objectId value is equal to a specific value.
Let me give you an example:
if the object id is equal to "-Kzx6b-w3cbE_3e1MwWr" then i would like to get the node value (-Kzx6bVxJHq0HgDjkhH8) so i can delte the record.
I tried to do it like so:
let query = Api.Notification.NOTIFICATION_REF.queryOrdered(byChild: "objectId").queryEqual(toValue: id)
query.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
print (snap.key)
}
However i get no value in the print statement Actually is seem not to enter at all the for cycle.
Is there a way to achieve this?
Thank you!
-----UPDATE
Would a solution like this affect the speed if i get many records?
Api.Notification.NOTIFICATION_REF.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
Api.Notification.NOTIFICATION_REF.child(key).observeSingleEvent(of: .value, with: { (userid) in
for subChild in userid.children {
let subSnap = subChild as! DataSnapshot
let subKey = subSnap.key
//get the value here
}
})
}
})
Use snap.ref.parent?.key
Example:
query.observe(.value, with: { snap in
guard let text = snap.value as? String else { return }
print("snap parent key: \(snap.ref.parent?.key)")
}