如何从Firebase提取特定数据并将其存储在字典中?

时间:2019-08-09 18:40:37

标签: swift firebase dictionary firebase-realtime-database

Database Structure我正在尝试从我的Firebase数据库中获取数据,以便我可以将其以字典的形式存储,该字典的类型为[String:[Any]],其中key是唯一ID,而值是一种数组类型,其数据存储在uniqueID->问题下。

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)
    })
}

此完成块为我提供:

[“-LlpbizBpQTXOQ6zv0zd”:[{     Qusetion =(         你好,         测试,         kkkkkkkkkkk     ); }]]]

相反,我怎么能获得

[“-LlpbizBpQTXOQ6zv0zd”:[您好,测试,kkkkkkkkkkk]]

1 个答案:

答案 0 :(得分:1)

您正在将值转换为字符串,而实际上它是一个JSON对象。这就是字典中的值是JSON对象的原因。

要仅获取Qusetion下的问题文本(典型值?),您需要遍历该子快照并收集各个值。像这样:

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)
})