Ad
How Can I Fetch Specific Data From Firebase And Store It In A Dictionary?
I'm trying to fetch data from my firebase database, such that i can store it in a form of dictionary which is a type [String: [Any]] where key is the unique id and the value is a type of array which has the data stored under uniqueID->Question.
func getData(currUser: String, completion: @escaping (([String : [Any]]) -> ())) {
var newArray = [String : [Any]]()
let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser)/Questions").observeSingleEvent(of: .value, with: { (snap) in
let enumerator = snap.children
while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{
newArray.updateValue([value], forKey: rest.key)
}
completion(newArray)
})
}
this completion block gives me:
["-LlpbizBpQTXOQ6zv0zd": [{ Qusetion = ( Hello, test, kkkkkkkkkkk ); }]]]
Instead how can i get
["-LlpbizBpQTXOQ6zv0zd": [Hello,test,kkkkkkkkkkk]]
Ad
Answer
You're converting the value to a string, while it's actually a JSON object. That's why the value in your dictionary is a JSON object.
To only get the question text under Qusetion
(typo?), you'll need to loop over that child snapshot and collect the individual values. Something like:
var newArray = [String : [Any]]()
let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser)/Questions").observeSingleEvent(of: .value, with: { (snap) in
let enumerator = snap.children
while let rest = enumerator.nextObject() as? DataSnapshot {
var values = [String]
let valueEnumerator = rest.childSnapshot(atPath: "Qusetion").children
while let valueRest = valueEnumerator.nextObject() as? DataSnapshot, let value = rest.value {
values.append(value)
}
newArray.updateValue([values], forKey: rest.key)
}
completion(newArray)
})
Ad
source: stackoverflow.com
Related Questions
- → How to write this recursive function in Swift?
- → Send email from a separated file using Swift Mailer
- → Laravel Mail Queue: change transport on fly
- → "TypeError: undefined is not an object" when calling JS function from Swift in tvOS app
- → Are Global/Nested functions in JavaScript implemented as closures?
- → JavascriptCore: executing a javascript-defined callback function from native code
- → Swift SHA1 function without HMAC
- → Shopify GraphQL using swift not getting response
- → How to disconnect git for a project in intellij?
- → Sending a request to a php web service from iOS
- → Add only objects that don't currently exist to Realm database
- → How to sort using Realm?
- → Realm object as member is nil after saving
Ad