未使用swift从Firebase的读取数据中接收错误信息

问题描述 投票:0回答:1

我设法使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个回答
0
投票

在某个位置没有数据不会在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)"
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.