As you can see from the image above underlined in red, I have a child that has a String value along with an Int Value. Now is it possible to retrieve only the String value? At the moment I'm using the code below but it retrieves the string and Int values not just the string value. I can't seem to figure how to isolate the string value. Any help would greatly appreciated. Thanks
Database.database().reference().child("likes").child(self.userUID).observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any]{
let uid = dictionary[""] as! String
print("uid")
}
})
Try this:
Database.database().reference().child("likes").child(self.userUID).observe(.value, with: { (snapshot) in
for child in snapshot.children {
let c = child as! FIRDataSnapshot
print(c.key)
}
})
Here your snapshot is the userid and then you add a for loop to iterate inside the children of the userid and get the key of those children in the print.
Example:
J2xb677oeCNhDMVW2WRwHeBzirM2
Related
Trying to get an array of child keys from Firebase
func getWavePosts() {
let wavePostRoot = Database.database().reference().child("waves_posts/\(self.waveLabel!)/")
wavePostRoot.observe(.value , with: {snapshot in
var tempKeys = [String]()
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key {
tempKeys.append(key as String)
}
}
self.tempNames = tempKeys
})
}
I've done this for values before but not keys, the append line is the one that is flagged. Inserting a line below the key initialization changes the error to "Generic parameter 'Element' could not be inferred". Any help would be much appreciated!
--------- edit without for loop ---------
let wavePostRoot = Database.database().reference().child("waves_posts/\(self.waveLabel!)/")
wavePostRoot.observe(.value , with: {snapshot in
var tempKeys = [String]()
self.tempNames.append(snapshot.key)
You want to do optional-binding but you forgot to if keyword. Also I think that you want to check if snap.key is of type String
if let string = snap.key as? String {
tempKeys.append(string)
}
I have a structure of database as on image and I need to display this date which is in the red rectangle. I tried to do smth like this, but it throws an error and I couldn't find same questions on a stack.
my database
reference.child("doc1").observe(.value, with: { (snapshot) in
if snapshot.exists() {
for date in (snapshot.value?.allKeys)
}
Your structure is a Dictionary of Dictionary so you have to cast your snap to [String:[String:Any]] where the key is your "11dot..." and value contains all hours
So try to use this code:
guard let dict = snap.value as? [String:[String:Any]] else { return }
for (key, value) in dict {
for (key2, value2) in value {
print(key2, value2) // this print your hours
}
}
Anyway I suggest you to don't use a observe(.value) which will read all change happened on all child node. Instead use the .childAdded feature of observer.
With a .childAdded you will receive only one child at a time (like a for on child node) and after that only the child added:
Database.database().reference().child("doc1").observe(.childAdded) { (snap) in
guard let dict = snap.value as? [String:Any]
print(dict) // this print data contains on "11dot10" and so on
}
Pictures
-pictureID
-- name
-- date
Like
-pictureID
-- userID: true
-- userID: true
likePerUser
-userID
--pictureID: true
--pictureID: true
Users
-userID
-- name
-- lastname
I would like to retrieve all picture that current user has liked.
I did:
ref.child("likePerUser").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snap) in
for item1 in snap.children{
let firstItem1 = (snap: item1 as! FIRDataSnapshot)
print("key favourites\(firstItem1.key)")
let firstId = firstItem1.key
self.ref.child("pictures").child(firstId).observeSingleEvent(of: .value, with: { (snapshot) in
for item in snapshot.children{
let firstItem = (snapshot: item as! FIRDataSnapshot)
print("key pictures \(firstItem.key)")
let dict = firstItem.value as! [String: Any
let name = dict["name"] as! String
print(name)
}
Even, If it seems that firstId has the right value each time,
I always get an error:
Could not cast value of type '__NSCFBoolean' (0x110dae5b8) to
'NSDictionary' (0x110daf288).
Please help....
I solved doing this:
if let dictionary = snapshot.value as? NSDictionary {
if let name = dictionary["nome"] as? String {
print(name)
}
}
This questions helped me: Swift - Could not cast value of type '__NSCFString' to 'NSDictionary'
Also i didn't need to iterate once more.
let dict = firstItem.value as! [String: Any
Here is where you attempt to cast a value as a dictionary. It's unclear whether the value is a dictionary based upon the model of the database you've shared. But there's a good chance that if you print firstItem.value.debugDescription, you will see that the value it isn't a dictionary object.
I'm a newbie to coding and Swift.
I'm trying to retrieve the value of house1Colour from my Firebase database in my app. I've tried these methods so far.
let eg = FIRDatabase.database().reference(withPath: "test")
(when I use this I get a THREAD 1 Signal SIGABRT error, I'm not sure why)
and:
var test:String!
FIRDatabase.database().reference().child("house1Colour").observeSingleEvent(of: .value, with: {(snap) in
if let snapDict = snap.value as? Dictionary <String, AnyObject>{
self.test = snapDict["house1Colour"] as! String
print(self.test)
}
})
None of them work.
The value of FIRDatabase.database().reference().child("house1Colour") is just the string since you already specified the key house1Colour.
Therefore you should be able to just:
if let snapString = snap.value as? String {
print(snapString)
}
I'm new to firebase and I have such structure of my firebase project
I want to get all objects, that "Interested" value is equal to "men"
I wrote such code, to get all object sorted by interes value:
let thisUserRef = URL_BASE.childByAppendingPath("profile")
thisUserRef.queryOrderedByChild("Interest")
.observeEventType(.Value, withBlock: { snapshot in
if let UserInterest = snapshot.value!["Interest"] as? String {
print (snapshot.key)
}
}
But I receive nil.
you need to loop through all the key-value profiles
if let allProfiles = snapshot.value as? [String:AnyObject] {
for (_,profile) in allProfiles {
print(profile);
let userInterest = profile["Interest"]
}
}
Here _ is the key that is in the format KYXA-random string and profile will be the element for that key.
Edit:
There is querying for child values as per the docs.
Try thisUserRef.queryOrderedByChild("Interest").equalTo("men") and then using the inner loop that i specified in the answer
This is a basic query in Firebase. (Updated for Swift 3, Firebase 4)
let profileRef = self.ref.child("profile")
profileRef.queryOrdered(byChild: "Interest").queryEqual(toValue: "men")
profileRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let dict = child as! [String: Any]
let name = dict["Name"] as! String
print(name)
}
})
The legacy documentation from Firebase really outlines how to work with queries: find it here
Legacy Firebase Queries
The new documentation is pretty thin.
Oh, just to point out the variable; thisUserNode should probably be profileRef as that's what you are actually query'ing.