swift - 当我启动 SnapshotListener 并将新数据放入本地数组时,我得到“Unexpectedly found nil while unwrapping an Optional value”
问题描述
我正在创建一个使用 Firebase 的 Firestore 数据库同步到云端的提醒应用。我正在关注本教程,并在 25:28 尝试将文档数据连接到本地数组(使用结构/字典)时遇到问题。当我运行该应用程序时,它会崩溃,突出显示该行,并说:
线程 1:致命错误:在展开可选值时意外发现 nil
那么,我该如何解决这个错误呢?我知道该教程有点旧(现在 2 年),但我找不到任何关于该主题的内容。错误出现在标题为检查更新的函数中
这是我现在拥有的代码:
import Foundation
import UIKit
import Firebase
class TableViewController: UITableViewController {
var DocRef: DocumentReference!
var db:Firestore!
var listArray = [ReminderLists]()
var list = [lists]()
var email:String?
var tableuserid:String?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
email = (Auth.auth().currentUser?.email!)!
tableuserid = Auth.auth().currentUser!.uid
db = Firestore.firestore()
let listsRef = db.collection("users").document(self.tableuserid!).collection("lists")
print("hey")
otherLoadData()
print("Done Loading. Listening...")
checkForUpdates()
}
//MARK: Loading Items
func LoadData(){
//let docRef = db.collection("users").document(self.tableuserid!).collection("lists")
db.collection("users").document("\(self.tableuserid!)").collection("lists")
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
self.listArray = querySnapshot!.documents.compactMap({ReminderLists(dictionary: $0.data())})
DispatchQueue.main.async {
print("Here you go!")
self.tableView.reloadData()
print(self.listArray)
}
}
}
}
}
func checkForUpdates(){
db.collection("users").document("\(self.tableuserid!)").collection("lists").addSnapshotListener {
querySnapshot, error in
guard let collection = querySnapshot else {return}
collection.documentChanges.forEach {
diff in
if diff.type == .added {
if diff.document.data().isEmpty == false {
self.listArray.append(ReminderLists(dictionary: diff.document.data())!)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} else {
print("Documents Were Empty!")
}
}
}
}
}
解决方案
推荐阅读
- file - 我的 Chromebook 中随机出现了一个文件夹
- c# - 有没有办法在 TestStack.White 中获取自定义控件类型中的所有元素
- python - Visual Studio,Python,命令“python setup.py egg_info”在 C:\Users\...\AppData\Local\Temp\pip-install-953alcay\rpy2\ 中失败,错误代码为 1
- c++ - 简单的 C++ 分词器
- android - SQLite 与外键 + 模型 Android Studio CRUD
- azure - 使用 MongoDB API 在 CosmosDB 中使用 Pyspark 部分更新文档
- mysql - 带有 LIMIT 和 GROUP BY 的 AVG
- python - 使用 tf.train.MonitoredTrainingSession 编写多个摘要
- c# - 使用 Newtownsoft,我如何序列化没有属性名称的对象?
- sql - 有没有更优雅的方式来重用代码块?