【问题标题】:Not receiving error information from read data in firebase using swift未使用 swift 从 firebase 中的读取数据中接收错误信息
【发布时间】:2020-03-23 05:11:05
【问题描述】:

我已经设法让 firebase 工作并从数据库中读取数据并呈现出来。

我正在拍照并让 CoreML 计算出该项目的内容,然后将其发送到数据库以返回有关该项目的数据。

如果该项目不在数据库 I 中,因此希望它出错,但返回只是空白。似乎firebase错误块根本不起作用,因为在执行代码的第一部分之后它没有到达。

我也尝试过使用 do catch 块,但没有成功。

请看附件代码:

    ref.child("items").child("\(self.final)").observeSingleEvent(of: .value, with: { (snapshot) in
    // Get item value

    let value = snapshot.value as? String ?? ""
    print(value)
    self.calorieCount.text = "\(value)"


   }) { (error) in
        print(error.localizedDescription)
        print("error")
        self.calorieCount.text = "Item not found, you will be able to add this soon"

}
}

谁能告诉我为什么当项目不在数据库中时错误部分不起作用?

提前致谢!

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    在某个位置没有数据不会被视为 Firebase API 中的错误,因此不会调用错误闭包。相反,您的常规闭包是用一个空的DataSnapshot 调用的,您可以对其进行测试:

    ref.child("items").child("\(self.final)").observeSingleEvent(of: .value, with: { (snapshot) in
        if !snapshot.exists() {
            self.calorieCount.text = "Item not found, you will be able to add this soon"
        }
        else {
            let value = snapshot.value as? String ?? ""
            self.calorieCount.text = "\(value)"
        }
    })
    

    【讨论】:

    • 非常感谢!我玩了这么多不同的选项,但什么都做不了,但当你知道怎么做时,它就是这么简单!
    • 差不多了,我只需要删除 !在 snapshot.exists() 之前,它起作用了!
    猜你喜欢
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多