observeSingleEvent不会触发

时间:2016-10-18 09:39:50

标签: json swift firebase firebase-realtime-database swift3

我一直试图弄清楚firebase如何在swift中工作。举个例子:

    let locationRef = FIRDatabase.database().reference(withPath: "Location")
    print("A")
    locationRef.observeSingleEvent(of: .value, with: { snapshot in
        print("B")
    })
    print("C")

使用firebase数据库:

{
    "Location" : [ {
        "address" : "100 Foo Avenue",
        "name" : "Foo"
     }, {
        "address" : "1800 Bar Street",
        "name" : "Bar",
     } ]
}

对我来说,无论我把observeSingleEvent(oSE)或放在oSE中的内容放在哪里,这段代码都不会打印B.根据文档,我认为oSE假设在运行时触发一次,然后在对firebase数据库进行任何更改时触发,但我无法触发它。在上一篇文章here中,我确实得到了它的工作,但我不知道如何,所以对oSE触发器的一些澄清将是惊人的!

2 个答案:

答案 0 :(得分:2)

首先,在定义引用时你做错了。引用应为FIRDatabase.database().reference().child("Location")

其次你对oSE的了解是正确的,但是你做错了。为什么在定义路径后打印(" A")?

总之试试这个:

let locationRef = `FIRDatabase.database().reference().child("Location")`
print("A")
locationRef.observeSingleEvent(of: .value, with: { snapshot in
    print(snapshot.value)//Just to show you what those prints
    print(snapshot.allKeys)//Just to show you what those prints
    print(snapshot.key)//Just to show you what those prints
})
print("C")

答案 1 :(得分:1)

如果您的位置字典上方有自动ID或任何未知ID,您可能想要使用它: -

let locationRef = FIRDatabase.database().reference().queryOrdered(byChild: "Location")
相关问题