首页 > 解决方案 > 即使 firebase 检索仍未完成,代码仍会继续执行

问题描述

我正在尝试从 Xcode 中的 firebase firestore 检索信息,将其放入列表中,然后将其显示在 CollectionView 中。

在我的firestore中,我有2个集合,用户和地点用户集合:有用户信息和他们访问的地点ID的集合地点集合:有地点信息,包括地点ID

因此,如果用户已登录,我将使用用户集合中的地点 ID 在 CollectionView 中显示他们的地点,以从 Places 集合中检索地点信息。

所以我所做的是进行两个嵌套查询,一个是从用户那里检索地点 ID,第二个是匹配 ID 并从 Places 集合中检索信息。此代码有效,但是速度非常慢,代码继续执行并在检索到所有信息之前完成,因此 CollectionView 中的列表保持为空。

    db.collection("users").document(userID).collection("placesList").getDocuments(){ (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for userdocument in querySnapshot!.documents {
                    self.db.collection(“Places”).document(userdocument.documentID+"").getDocument(){ (document, error) in
                        if let document = document, document.exists {
                            let place = Place(ID: document.documentID, name: document.get("name") as! String, rate: document.get("rating") as! Double, long: document.get("longitude") as! Double, lat:document.get("latitude") as! Double)

                            self.list.append(place)

                        } else {
                            print("Document does not exist")
                        }//end else
                    }
                }//end second query
        }//end else
    }// end first query

我不明白这段代码的问题,有没有更好的方法呢?!或者如何在完成查询之前停止执行代码?

标签: swiftfirebasecollectionsgoogle-cloud-firestore

解决方案



推荐阅读