Ad

How Can I Fetch Specific Data From Firebase And Store It In A Dictionary?

Database StructureI'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
Ad