即使Firebase检索仍未完成,代码仍继续执行

时间:2020-03-22 23:53:30

标签: swift firebase collections google-cloud-firestore

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

在我的Firestore中,我有2个收藏集,用户和地点 用户集合:具有用户信息和他们访问过的地点ID的集合 地点集合:具有包含地点ID的地点信息

因此,如果用户已登录,我将使用用户集合中的位置ID在CollectionView中显示其位置,以从位置集合中检索位置信息。

所以我要做的是进行两个嵌套查询,一个是从用户那里检索位置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

我不了解此代码的问题,有更好的方法吗?还是在完成查询之前如何停止执行代码?