首页 > 解决方案 > 当我启动 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!")
                    }

                }

            }
        }
    }

标签: swiftfirebasedictionarystruct

解决方案


推荐阅读