ios - Swift - 使用 DispatchGroup() 从 Firebase Firestore 异步下载数据时出现问题

标签 ios swift firebase

在获取“事件”集合中每个文档的 ID(其中它们的 EventStatus 值等于 0)并将它们存储在字符串数组 (documentIds) 中时,我尝试使用 DispatchGroup() 异步运行代码,因此当我返回“documentIds”时,我会返回一个非空且完整的值。

但是当我运行下面的代码时,它卡住了,实际上它从未在 getDocuments{} 闭包中运行。

我尝试在 DispatchQueue.global().async{} 中运行 getDocuments{} 闭包,但它也不起作用。

func someFunction() -> [String] {

var documentIds : [String]!
var dispatchGroup = DispatchGroup()
dispatchGroup.enter()

Firestore.firestore().collection("events").whereField("EventStatus", isEqualTo: 0).getDocuments { (snap, error) in

        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let snap = snap else { return }

        documentIds = snap.documents.map({ (document) -> String in
            return document.documentID
        })

        dispatchGroup.leave()

    }

dispatchGroup.wait()
return documentIds

}

当它卡住时,firebase 在调试控制台中给出了这个错误:

“无法连接到 Cloud Firestore 后端。后端在 10 秒内没有响应。 这通常表示您的设备目前没有正常的互联网连接。客户端将以离线模式运行,直到它能够成功连接到后端。”

除此之外,没有错误或其他一些反馈。我对 DispatchGroup() 或 Firestore 做错了吗?

提前感谢您的帮助!

最佳答案

这是 dispatchGroup 无用并导致许多错误的情况之一。

由于从 Firestore 检索数据是异步调用,因此请为您的方法使用完成处理程序而不是返回值并摆脱 dispatchGroup

func someFunction(completion: @escaping ([String]) -> Void) {

    Firestore.firestore().collection("events").whereField("EventStatus", isEqualTo: 0).getDocuments { snap, error in

        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let snap = snap else { return }

        var documentIds = snap.documents { document in
            return document.documentID
        }

        completion(documentIds)
    }

}

然后使用完成处理程序调用您的方法,您可以在其中访问接收到的 String

数组
someFunction { documentIds in // name completion parameter of type `[String]`
    ... // assign some global array as `documentIds` and then reload data, etc.
}

关于ios - Swift - 使用 DispatchGroup() 从 Firebase Firestore 异步下载数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097857/

相关文章:

Swift:使用闭包减少函数

ios - UIAlertController/ActionSheet 在 iPad 上崩溃,如何传递发件人?

java - 如果已知值,如何在 firebase 数据库中找到键?

node.js - 以 Firebase 用户身份使用 Node.js 访问 Firebase 存储

objective-c - iOS/越狱上的 tcpdump

ios - 在iOS上混合和均衡多个压缩音频流

iphone - 是否可以从远程浏览器连接到我的 CocoaHttpServer?

ios - 在 iOS 上扫描蓝牙 2.1(旧版)设备

android - 使用 Firestore 按键入的字母搜索

ios - 如何检测像 Maps.app 这样的 MKPolylines/Overlays 上的点击?