Reputation:
Trying to come up with some logic that could help in documenting few resources for firebase. Have looked up few resources in regards to the problem, this question somewhat resembles the issue but not to the extend to solve it. SimillarQuestion . And the avilable doc doesn't mention any logic to implement it either GoogleDoc.
How to get only the keys from a given firebase json tree? As they say a pic tells thousand words. Have got the below mentioned tree for firebase setup. And at mentioned is the required out put where it is displayed to the user in a table view.
--uniUsers
|
|Fruits
| |
| |Apple:true
| |Kiwi:true
| |Orange:true
|
|Veggies
|
|Carrot:true
|Onions:true
|Lettuce:true
Swift Code
func fetchTotalUsers(){
let tempUniId = "Fruits"
let refUniId = Database.database().reference(withPath: "UniUsers/\(tempUniId)")
refUniId.observe(.value, with: { (snapp) in
print("Value><", snapp.key)
print("Key><", snapp.value!)
}
}
Swift OutPut:
Value >< Fruits
Key >< {
Apple = 1;
Kiwi = 1;
Orange = 1;
}
Required Output
Apple
Kiwi
Orange
Upvotes: 1
Views: 1079
Reputation:
Found by using enumeration we can go step by step but for a newbie the answer selected makes more sense in terms of readability unless the concept of enumeration is known before
refUniId.observe(.value, with: { (snapp) in
print("Count><", snapp.childrenCount)
let enumeratorRR = snapp.children
while let rest = enumeratorRR.nextObject() as? DataSnapshot{
print("GotRequiredFruits",rest.key)
}
}
Upvotes: 0
Reputation: 3606
You can use keys
property .
From official documentation here
keys
A collection containing just the keys of the dictionary.
Again from the official documentation:
When iterated over, keys appear in this collection in the same order as they occur in the dictionary’s key-value pairs. Each key in the keys collection has a unique value.
So in your particular case you can do some thing like this:
Since you get dictionary from the firebase server
refUniId.observe(.value, with: { (snapp) in
print("Value><", snapp.key)
print("Key><", snapp.value!)
if let dict = snapp.value as? [String: Any] {
for k in dict.keys {
print(k)
}
}
}
Upvotes: 1