首页 文章

Firebase快照返回null

提问于
浏览
0

嗨,大家好我一直在使用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)
            }
        })
    }
}

这是我试图检索的路径的 Value

产品/实时/全球/ WpMvDJZUclRlfHFJsSlBEbi0jHf1

这是firebase数据库的快照

enter image description here

snapshot.value alwasy在swift中返回null . 当我打印使用

print("Snap: \(snapshot.value)")

它打印以下内容

Snap:可选()请指导我做错了什么,以便我能够做到 .

1 回答

  • 3

    如果您正在使用.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!)
    }
    

相关问题