ios - Firestore 查询在创建新文档时未收到更新

标签 ios swift firebase google-cloud-platform google-cloud-firestore

我有一个 Firestore 查询,我需要它来监听新文档的创建,我尝试了很多可能性但无法使其工作,每次我创建文档时都不会触发监听器。这是我的监听器代码:

firestore
        .collection("users")
        .document("123")
        .collection("images")
        .whereField("postId", isEqualTo: "123")
        .order(by: "createdAt", descending: true)
        .limit(to: 1)
        .addSnapshotListener { [weak self] snapshot, error in
            guard let imageDocument = snapshot?.documents.first else {
                return
            }
            // this print statement is only being called once (not being called when creating a new doc)
            print(imageDocument)
        }
...

这是我创建文档的查询:

firestore
    .collection("users")
    .document("123")
    .collection("images")
    .document()
    .setData([
        "postId": "123",
        "imageUrl": "....",
        "createdAt": Timestamp()
    ]) { error in
       guard let error = error else { return }
       print(error)
    }

我的目标是当我在 Firestore 中创建新文档时触发此监听器。

此外,如果我从我的监听器查询中删除限制,代码可以工作,但我会不必要地花费大量读取。

最佳答案

问题不在于将数据添加到 Firestore 的方式,而在于读取数据的方式。也没有与“limit(to: 1)”调用相关的内容。当您执行以下查询时:

firestore
    .collection("users")
    .document("123")
    .collection("images")
    .whereField("postId", isEqualTo: "123")
    .order(by: "createdAt", descending: true)
    .limit(to: 1)

这意味着你想从“images”子集合中获取“postId”字段值为“123”的所有文档,然后根据“createdAt”字段对结果进行排序降序并将结果限制为“1”。

为了能够进行这样的查询,您必须创建一个 index对于它,否则,它不会返回任何结果。您可以在 Firebase Console 中手动创建所需的索引:

enter image description here

或者您会在 IDE 中找到如下所示的消息:

FAILED_PRECONDITION: The query requires an index. You can create it here: ...

您只需单击该链接或将 URL 复制并粘贴到网络浏览器中,系统就会自动为您创建索引。

代码应该保持不变。

关于ios - Firestore 查询在创建新文档时未收到更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308228/

相关文章:

swift - Firestore 收集监听器大量读取

javascript - React Native Firebase如何从特定用户的表数组中获取数据

ios - 如何在以前为 iPhone 构建的应用程序中为 iPad 添加 .xib 文件?

ios - Crashlytics:如何在崩溃详细信息中查看用户名/电子邮件/ID?

c++ - 如何制作从 C++ 到 Swift 的回调函数指针?

ios - 如何同步 AVPlayer 和 MTKView

ios - 如何设置变量以从 Swift 中的 Firebase 数据库结构中获取值

ios - 在 UIDatePicker 上设置时间范围

ios - 如何在 iOS Swift 4 中为 UITableView 的部分设置阴影?

ios - 谷歌地图 iOS SDK : Map not loading although it's enabled and the key is correct