ios - Swift 从数据库检索 Firebase 数据

标签 ios swift firebase firebase-realtime-database

我正在尝试从 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/

相关文章:

ios - 无法获取Parse block 中NSLog的来源?

ios - 两个 Segue 从一个 View Controller 传递相同的数据

ios - 尝试播放音频时出错 : 998: Failure to setup sound, err = -50

android - Firebase 到自定义 Java 对象

Android 项目,更改 Firebase 帐户

reactjs - 如何在 Google Cloud Firestore 中使用点表示法中的变量

ios - 与文件应用程序共享应用程序文档中的特定目录

ios - 什么时候在 Swift 中使用@objc?

swift - 将 Swift 用于 Mac 应用程序的优缺点是什么?

ios - 如何在新 View 中显示 UISearchController 结果而不显示 tableView 的背景?