swift firestore将用户追加到数组-完成块

时间:2018-11-23 09:08:19

标签: swift google-cloud-firestore

我试图在self.setupDummyCards()完成将所有用户追加到self.cardViewModels.append(user.toCardViewModel())数组之后调用函数CardViewModels,尽管我不知道该放在哪里?

fileprivate func fetchUsersFromFirestore() {
    guard let uid = Auth.auth().currentUser?.uid else { return }


    Firestore.firestore().collection("Users").document(uid).collection("Following").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                let d = document.data()
                d.forEach({ (key: String, value: Any) in



                Database.firestorefetchUserForTinderCardWithUID(uid: key, completion: { (user) in

            self.cardViewModels.append(user.toCardViewModel())

//below it is called after each user is appended, meaning it appends the same users again and again until the last user is add
                   self.setupDummyCards()
                })
          //here is called before self.cardViewModels.append(user.toCardViewModel())
        })

        //here is called before self.cardViewModels.append(user.toCardViewModel())            

    }
      //here is called before self.cardViewModels.append(user.toCardViewModel())
}
//here is called before self.cardViewModels.append(user.toCardViewModel())
    }
  //here is called before self.cardViewModels.append(user.toCardViewModel())
}

1 个答案:

答案 0 :(得分:0)

我刚得到documents.count,然后仅在documents.count等于cardViewModels.count时才调用self.setupDummyCards()

   fileprivate func fetchUsersFromFirestore() {
    guard let uid = Auth.auth().currentUser?.uid else { return }
   Firestore.firestore().collection("Users").document(uid).collection("Following").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {

                let dc = querySnapshot?.documents.count

                for document in querySnapshot!.documents {
                let d = document.data()



                d.forEach({ (key: String, value: Any) in



                Database.firestorefetchUserForTinderCardWithUID(uid: key, completion: { (user) in

            self.cardViewModels.append(user.toCardViewModel())

                    if self.cardViewModels.count == dc {
                   self.setupDummyCards()
                    }
                })

        })



    }

}
    }

}