繁体   English   中英

Swift - 从 Firestore 获取元素

[英]Swift - Fetch elements from Firestore

我对这个 function 有疑问:

func fetchGameFromDB(completionHandler: @escaping ([GamesObject]) -> Void) {


    db.collection("games").getDocuments { (querySnapshot, err) in
        if let err = err {
            print("Error: \(err)")
        } else {
            self.gameObject = []
            for document in querySnapshot!.documents {
                print("document \(document.data())")
                if let name = document.data()["name"] as? String {
                    let docRef = self.db.collection("games").document(name)
                    docRef.getDocument { document, error in
                        if let document = document {
                            let data = document.data()
                            let name = data?["name"] as? String ?? ""
                            let urlStanding = data?["urlStanding"] as? String ?? ""
                            let img = data?["gameImg"] as? String ?? ""
                            let urlUpcoming = data?["urlUpcoming"] as? String ?? ""
                            self.gameObject.append(GamesObject(name: name, gameImg: img, urlStanding: urlStanding, urlUpcoming: urlUpcoming))
                            // here i have elements in gameObject
                        }
                        // here i have elements in gameObject
                    }
                    // here gameObject = []
                }
                // here gameObject = []
            }
            completionHandler(self.gameObject)
            // here gameObject = []
        }
    }
}

我很好地获取了数据并将其添加到我的数组中,但是当我到达 completionHandler 时,数组为空。

我找到解决方案,我检查是否 gameObject.count == querySnapshot?.count 然后我使用我的 completionHandler

func fetchGameFromDB(completionHandler: @escaping ([GamesObject]) -> Void) {
    db.collection("games").getDocuments { (querySnapshot, err) in
        if let err = err {
            print("Error: \(err)")
        } else {
            self.gameObject = []
            querySnapshot?.documents.forEach({ (document) in
                if let name = document.data()["name"] as? String {
                    let docRef = self.db.collection("games").document(name)
                    docRef.getDocument { document, error in
                        if let document = document {
                            let data = document.data()
                            let name = data?["name"] as? String ?? ""
                            let urlStanding = data?["urlStanding"] as? String ?? ""
                            let img = data?["gameImg"] as? String ?? ""
                            let urlUpcoming = data?["urlUpcoming"] as? String ?? ""
                            self.gameObject.append(GamesObject(name: name, gameImg: img, urlStanding: urlStanding, urlUpcoming: urlUpcoming))
                            if self.gameObject.count == querySnapshot?.count  {
                                completionHandler(self.gameObject)
                            }
                        }
                    }
                }
            })
        }
}

}

第一个答案只要不存在丢失的文件就没有问题。 但是,如果缺少任何文件,则无法逃脱。

使用'DispatchGroup'怎么样?

func fetchGameFromDB(completionHandler: @escaping([GamesObject]) -> Void) {

    db.collection("games").getDocuments { (querySnapshot, error) in 
        guard let docs = querySnapshot?.documents, !docs.isEmpty else {
            if let error = error {
                print(error)
            }
            
            return
        }

        let group = DispatchGroup()
        docs.forEach { doc in 
            group.enter()

            guard let name = doc.data()["name"] as? String else {
                group.leave()
                return
            }

            let docRef = self.db.collection("games").document(name)
            docRef.getDocument { document, error in 
                if let document = document, let data = document.data() {

                    //do something...
                    
                    gameObjects.append(GamesObject(...)) //init object
                }
                
                group.leave()       
            }
        }

        group.notify(queue: .main) {
            completionHandler(gameObjects)
        }
    }        
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM