我有一个函数将文档添加到 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/