简体   繁体   中英

swift firestore appending users to array - completion block

I am trying to call the function self.setupDummyCards() after self.cardViewModels.append(user.toCardViewModel()) has finished appending all users to CardViewModels Array though i can't figure out where to put it?

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())
}

i just got documents.count and then only called the self.setupDummyCards() once documents.count was equal to cardViewModels.count

   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()
                    }
                })

        })



    }

}
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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