首页 > 解决方案 > 使用 swift 4 从 ios 监听 Firestore 中的实时更新

问题描述

我正在尝试收听集合中特定文档的创建,然后在发生更改后打印文档数据。仅当关闭应用程序或创建文档时,此侦听才应停止。

我尝试使用文档中的代码,但根据经验发现,即使文档不存在,在使用 print 语句执行一次后监听也会停止 - “文档数据为空”。

        let uid = "DocumentID"
        let db = Firestore.firestore()
        db.collection("MyCollection").document(uid!)
        .addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                return
            }
            guard let data = document.data() else {
                print("Document data was empty.")
                return
            }
            let data = document.data()
            print("Current data: \(String(describing: data))")

我需要的代码可以等到在集合中创建文档,然后在其中打印文档 ID 先前已知的数据。

标签: iosxcodegoogle-cloud-firestoreswift4

解决方案


推荐阅读