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

时间:2019-10-25 13:37:17

标签: 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个字段,如果有任何区别的话。

3 个答案:

答案 0 :(得分:0)

编辑:

也许您可以运行完成处理程序,以使出口与小组位于同一位置?我通常会在这种情况下编写完成处理程序,并在您有self.dispatchGroup.leave()的地方调用它们。您可以将self.dispatchGroup.leave()放在完成框中,这可能有帮助?看来您的小组的入口点和出口点数量不均衡。使用完成块进行组织可能会帮助找到它?

completion: (@escaping (Bool) -> ()) = { (arg) in })

原文:

您介意使用此setData代码而不是addDcoument来查看是否有帮助?您可以将分派添加到此代码中,然后查看是否全部正常。如果没有,我会继续考虑下去...

还可以检查以确保输入数组不为空(只需将其打印到方法中的控制台上即可)。

     let db = Firestore.firestore()

     db.collection("your path").document("\(your document name)").setData([
         "aName": "\(name)",
         "anEmail": "\(email)",
     ]) { err in
         if let _ = err {
             print("Error writing document:")
         } else {
             print("Document successfully written!")
         }
     }

答案 1 :(得分:0)

有很多方法可以做到这一点-这是两种。首先是使用调度组,其次是使用和索引技术。

我有一个单词数组,想将它们写到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")
            }
        })
    }
}

答案 2 :(得分:0)

  

我的问题是完成处理程序似乎从未被调用为   消息永远不会被打印出来。

至少在成功添加文档的情况下,看来您没有在TIME'06:00:00;方法中调用completion