我正在尝试从 Firebase 检索数据,但遇到问题。
let refEmployees = Database.database().reference(withPath: "Employees")
refEmployees.child("Logan").observeSingleEvent(of: .value, with: {
snapshot in
let shift = snapshot.value as? String
self.shifts.append(shift!)
self.workSchedule.reloadData()
})
这是我的代码,我的数据库看起来像 this .
当我运行它时,我得到
fatal error: unexpectedly found nil while unwrapping an Optional value
有什么想法吗?我很困惑。我还可以同时向数据库添加信息并更改为 childAdded
并且信息正确加载。
最佳答案
通常我从来不会尝试获取引用“withPath”,而是通过子进程。 我会尝试这样做:
let ref = Database.database().reference().child("Employees").child("Logan")
另一方面,强制展开您不知道实际上会得到的选项是一种不好的做法,我会将闭包更改为:
ref.observeSingleEvent(of: .value, with: {
snapshot in
guard let shift = snapshot.value as? String else {
print("Value is Nil or not String")
return
}
self.shifts.append(shift)
self.workSchedule.reloadData()
})
就像评论中的某人所说,首先打印可选值可能是个好主意,看看您是否确实从数据库中获取了所需的值。
希望这有帮助
关于ios - Swift 从数据库检索 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45268730/