Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 我如何异步初始化firebase firestore侦听器,同时也知道所有任务何时完成?_Swift_Firebase_Asynchronous_Grand Central Dispatch - Fatal编程技术网

Swift 我如何异步初始化firebase firestore侦听器,同时也知道所有任务何时完成?

Swift 我如何异步初始化firebase firestore侦听器,同时也知道所有任务何时完成?,swift,firebase,asynchronous,grand-central-dispatch,Swift,Firebase,Asynchronous,Grand Central Dispatch,基本上,在我的应用程序发布时,我想从firebase加载来自大约4-5个不同文档的最新数据。然后我还想设置一个监听器来监视数据更改。为此,我调用了4-5个类似的函数,这些函数将dispatchGroup作为参数。我可能是完全错误的,但我想不出任何其他方法来做到这一点。我只想加载这些文档,设置侦听器,并在应用程序启动时加载这些文档时采取某些操作 //应用程序发布 let dispatch = DispatchGroup() getFirebaseDocument1(dispatch: dispa

基本上,在我的应用程序发布时,我想从firebase加载来自大约4-5个不同文档的最新数据。然后我还想设置一个监听器来监视数据更改。为此,我调用了4-5个类似的函数,这些函数将
dispatchGroup
作为参数。我可能是完全错误的,但我想不出任何其他方法来做到这一点。我只想加载这些文档,设置侦听器,并在应用程序启动时加载这些文档时采取某些操作

//应用程序发布

let dispatch = DispatchGroup()

getFirebaseDocument1(dispatch: dispatch)
getFirebaseDocument2(dispatch: dispatch)
getFirebaseDocument3(dispatch: dispatch)
getFirebaseDocument4(dispatch: dispatch)
getFirebaseDocument5(dispatch: dispatch)


dispatch.notify(queue:main) {
// execute some code to execute after all the documents are fetched
}




// typical getFirebaseDocument code

dispatch.enter()

let ref = someFirestoreReference

ref.addSnapshotListener { (snapshot, error) in
if let error = error{
   // handle error
} else {
// load the document



}
dispatch.leave()

}

该代码在启动时工作正常,但在侦听器收到更新时崩溃。我知道这是因为侦听器函数中调用了
dispatch.leave()
。然而,我似乎无法找到一个聪明的解决方案,在启动时可以从firebase异步加载数据,同时设置侦听器。我也不希望将闭包嵌套在另一个闭包中,因为这不是异步的,而且也会很痛苦。

我可能错了,但您应该将组留在块中,下面是我如何使用组进行嵌套的示例

class func getRates(completion: @escaping EmptyBlock) {
    let eurRequest = APIConfigs.request(part: "rs/price/history")
    let usdRequest = APIConfigs.request(part: "rs/price/history/usd")
    let group = DispatchGroup()
    group.enter()
    sendRequest(request: eurRequest, method: .get, parameters: ServerParameters.rates()) { response in
        Course.current.addRate(rates: ratesRequest(response: response), type: .eur)
        group.leave()
    }
    group.enter()
    sendRequest(request: usdRequest, method: .get, parameters: ServerParameters.rates()) { response in
        Course.current.addRate(rates: ratesRequest(response: response), type: .usd)
        group.leave()
    }

    group.notify(queue: .main) {
        completion()
    }
}