swift - 未使用 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"
}
}
有人能告诉我为什么当项目不在数据库中时错误部分不起作用?
提前致谢!
解决方案
在某个位置没有数据不会被视为 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)"
}
})
推荐阅读
- reactjs - 水平地图材质 UI 网格
- javascript - 排序数组中缺少整数
- linux - x86_64-conda_cos6-linux-gnu-cc: 错误: 无法识别的命令行选项'--showme:link'; 您的意思是“--force-link”吗?
- html - 在 div 元素中剪切线
- javascript - React Router Dom 升级错误 - 元素类型无效:应为字符串
- radius - hostapd v2.9 上的 MACsec 设置问题
- caching - 直接映射缓存与设置关联缓存
- python - Azure AD 与容器中运行的 Flask 集成的 PermissionError
- python - 布尔值总是返回为真?(熊猫)
- python - 在 NVIDIA Jetson TX2 上运行的 ultralytics yolov5 的非法指令(核心转储)