首页 > 解决方案 > 未使用 swift 从 firebase 中的读取数据中接收错误信息

问题描述

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

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

如果该项目不在我的数据库中,因此希望它出错,但返回只是空白。似乎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"

}
}

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

提前致谢!

标签: swiftfirebasefirebase-realtime-database

解决方案


在某个位置没有数据不会被视为 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)"
    }
})

推荐阅读