swift - addDocument 完成处理程序永远不会被调用

标签 swift firebase google-cloud-firestore

我有一个函数将文档添加到 firebase 中的集合中。它是使用 for 循环完成的。我有一个 DispatchGroup,并且在循环的每次迭代开始时调用 Enter() 。添加每个文档后,我想调用 addDocument 方法的完成处理程序。在完成处理程序中,我想在 DispatchGroup 上调用leave(),以便最终可以在添加所有文档后执行segue。我的问题是,完成处理程序似乎永远不会被调用,因为消息永远不会被打印。我可以看到每次运行代码时这些文档都会添加到我在 firebase 中的集合中。我是否误解了什么或者我的方法有问题?任何帮助将不胜感激。我的代码的简化示例如下所示:

func uploadDocumentToFirebase(names: String[])
    {   
        for name in names
        {
            dispatchGroup.enter()

            collection.addDocument(data: ["name": name], completion: {error in

                print("Document: \(name) was uploaded to firebase")

                self.dispatchGroup.leave()
            })
        }
    }

我添加的实际文档有 6 个字段,而不是我的示例中显示的 1 个字段(如果这有什么区别的话)。

最佳答案

有很多方法可以做到这一点 - 这里有两种。第一个是使用调度组,第二个是使用索引技术。

我有一组单词,想要将它们写入 Firestore,在每个单词写入时发出通知,然后在全部写入时发出通知。

let arrayOfWords = ["boundless", "delicious", "use", "two", "describe", "hilarious"]

这是调度组代码。我们进入组,写入数据并在完成处理程序中,完成后离开。当所有内容都离开后,将调用 group.notify。

func writeWordUsingDispatchGroup() {
    let group = DispatchGroup()
    let wordCollection = self.db.collection("word_collection")

    for word in self.arrayOfWords {
        group.enter()
        let dataToWrite = ["word": word]
        wordCollection.addDocument(data: dataToWrite, completion: { error in
            print("\(word) written")
            group.leave()
        })
    }

    group.notify(queue: .main) {
        print("all words written")
    }
}

然后是索引代码。这一切所做的就是计算数组中最后一个对象的索引,然后迭代枚举的数组(因此我们得到了索引)。然后,当当前循环的索引与最后一个索引匹配时,我们就知道我们已经完成了。

func writeWordsUsingIndex() {
    let wordCollection = self.db.collection("word_collection")
    let lastIndex = self.arrayOfWords.count - 1
    for (index, word) in self.arrayOfWords.enumerated() {
        let dataToWrite = ["word": word]
        wordCollection.addDocument(data: dataToWrite, completion: { error in
            print("\(word) written")

            if index == lastIndex {
                print("all words written")
            }
        })
    }
}

关于swift - addDocument 完成处理程序永远不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58559639/

相关文章:

c# - Firestore C# : Missing or insufficient permissions

javascript - 如何在 HTML 表格上显示带有多级键的 Firebase 数据?

firebase - 如何在使用 IMPORTRANGE 的 Google 表格中将持续时间转换为秒

ios - UITextField - 返回时向下滚动

ios - 关闭键盘迫使我长按表格 View 中的单元格

android - Firebase setOffline() 和读取离线数据 (android)

firebase - 为什么 persistenceEnabled : true result in my queries giving incorrect results?

javascript - 为什么这些查询独立工作而不是一起工作?

Swift Data.subdata 因 EXC_BAD_INSTRUCTION 而失败(代码=EXC_I386_INVOP,子代码=0x0)

Swift:调用函数似乎令人困惑