如何合并两个Firebase快照

时间:2016-08-11 10:22:24

标签: swift firebase firebase-realtime-database nested-queries

我在Firebase中运行嵌套查询(使用Swift)。这将返回两个快照。通常,当只有一个快照时,我会将查询结果存储在字典中

var query1 = [FIRDataSnapshot]! = []
query1.append(snapshot)

有谁知道如何合并两个快照来创建单个词典条目? 这些块看起来像这样:

_refHandle = FirebaseRef.child("query1key").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
    let key2 = snapshot.value?.objectForKey("key2") as! String
    self.FirebaseRef.child("query2key").child(key2).observeSingleEventOfType(.Value, withBlock: { (snapshot2) in
        // merge the two snapshots
   })
})

1 个答案:

答案 0 :(得分:1)

一旦两个快照都可用,您可以从中获取必要的值并根据该信息创建新对象。

class MergedObject {
    var value1: String!
    var value2: String!

    init(value1: String!, value2: String!) {
        self.value1 = value1
        self.value2 = value2
    }        
}

然后将该对象添加到词典中。

_refHandle = FirebaseRef.child("query1key").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
    let key2 = snapshot.value?.objectForKey("key2") as! String
    self.FirebaseRef.child("query2key").child(key2).observeSingleEventOfType(.Value, withBlock: { (snapshot2) in
        var value1 = snapshot.childSnapshotForPath("value1").value as! String
        var value2 = snapshot2.childSnapshotForPath("value1").value as! String
        var mergedObject = MergedObject(value1: value1, value2: value2)
   })
})