ios - Firebase 快照返回 null

标签 ios swift firebase firebase-realtime-database

大家好,我一直在使用 firebase 从数据库中写入和读取值。在我编写一个函数来检索以下列方式使用 swift 存储的值或产品之前,它的工作非常棒。

这是我的代码

func retrieveLiveUrlFor(product: Product){
    if let path = product.prodRef{
        print("Looking for : \(path)")
        var liveUrl = ""
        let ref = Database.database().reference(withPath: path)
        ref.observe(. value, with: {
            snapshot in
            print("Snap : \(snapshot.value)")
            if snapshot.exists(){
                print("Snap : \(snapshot.value)")
                let dic = snapshot.value as? NSDictionary
                if dic != nil{
                    let url = dic?["liveUrl"] as? String
                    print("Url is here")
                    if url != nil{
                        print("URL is not nil")
                        liveUrl = url as! String
                    }
                }
            }

            if (self.productdelegate != nil){
                print("Calling Product delegate")
                self.productdelegate?.liveUrlObtained!(liveUrl: liveUrl)
            }
        })
    }
}

这是我要检索的路径的值

Products/Live/Global/WpMvDJZUclRlfHFJsSlBEbi0jHf1

这是 firebase 数据库的快照

enter image description here

snapshot.value 总是在 swift 中返回 null。 当我使用

打印时
print("Snap: \(snapshot.value)")

打印如下

Snap : Optional() Please guide me what I am doing wrong so that I can get to it.

最佳答案

如果您使用 .value 事件进行观察,则返回 snapshot.value 为 nil 意味着快照值在该引用中不存在。尝试打印整个快照和 snapshot.key

理想情况下,您需要的引用是

  let ref = Database.database.reference().child("Products").child("Live").child("Global").child("WpMvDJZUclRlfHFJsSlBEbi0jHf1")

观察者的功能如下:

ref.observe(.value) {(snapshot) in
print(snapshot.value!)
}

关于ios - Firebase 快照返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600424/

相关文章:

ios - 更改iPad音量不影响App

iphone - XML PList 到 JSON 转换器并在客户端处理 JSON 响应

ios - 从解析的 XML 将数据加载到 TableView

ios - 类型 "Entity"的值没有成员 'text'

firebase - 聚合物 1.x + Firebase 2.x : How to push or put data to Firebase using Polymerfire?

iphone - ios 多级首选项 Pane

ios - View 不显示和自动布局集中

swift - 错误 - 带有 top 命令的 NSTask

android - 查询添加文档但未在控制台上添加,也未调用监听器

javascript - for循环中的异步变量