【问题标题】:Swift - Problem While Downloading Data From Firebase Firestore Asynchronously with DispatchGroup()Swift - 使用 DispatchGroup() 从 Firebase Firestore 异步下载数据时出现问题
【发布时间】:2019-01-08 18:45:51
【问题描述】:

在“events”集合中获取每个文档的 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 上做错了吗?

提前感谢您的帮助!

【问题讨论】:

    标签: ios swift firebase


    【解决方案1】:

    这是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.
    }
    

    【讨论】:

    • 非常感谢罗伯特!这是有道理的,而且效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2018-04-10
    • 2021-07-22
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多