从查询中快速Swift Firestore自定义对象,同时使用快照监听器监听实时更新

时间:2020-05-03 08:53:31

标签: swift firebase google-cloud-firestore swiftui

querySnapshots发生的snapshotListener转换为自定义对象时遇到问题。

这是我的代码,但是编译器在抱怨:

func getCartData(db: Firestore){
        db.collection("test")
        .whereField("Cart", arrayContains: "testItem")
        .addSnapshotListener { querySnapshot, error in
            guard let documents = querySnapshot?.documents else {
                print("Error fetching document: \(error!)")
                return
            }
            for doc in documents {
                guard let data = doc.data() else { //here is an error saying: Initializer for conditional binding must have Optional type, not '[String : Any]'
                  print("Document data was empty.")
                  return
                }

                let result = Result {
                  try doc.data(as: CartDataDocument.self)
                }
                switch result {
                case .success(let userDataDoc):
                    if let userDataDoc = userDataDoc {
                      // A `userDataDoc` value was successfully initialized from the DocumentSnapshot.
                      self.cartData = userDataDoc
                    } else {
                      // A nil value was successfully initialized from the DocumentSnapshot,
                      // or the DocumentSnapshot was nil.
                      print("Document does not exist")
                    }
                case .failure(let error):
                    // A `userDataDoc` value could not be initialized from the DocumentSnapshot.
                    print("Error decoding UserDataDocument: \(error)")
                }
            }
        }
    }

我能够创建一个Firestore文档的自定义对象,该文档使用snapshotListener进行了监听,但是此查询没有运气。

1 个答案:

答案 0 :(得分:1)

错误似乎正确。如果您查看Xcode在自动填充时显示的声明,则doc.data()确实是不可为空的[String: Any]

如果要检查文档是否为空,可以这样操作:

guard !doc.data().isEmpty else {
    print("Document data was empty.")
    return
}

否则,您也可以在CartDataDocumentoverride init(from decoder: Decoder) throws并为所有键提供默认值。 这显然是朝着另一个方向发展的:您将不忽略空文档,而是使用默认值将它们添加到列表中。但是我要问:为什么您有空文件?