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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 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())
}
答案

我刚刚获得documents.count,然后只有在document.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()
                    }
                })

        })



    }

}
    }

}

以上是关于swift firestore将用户附加到数组 - 完成块的主要内容,如果未能解决你的问题,请参考以下文章

Firestore 将具有服务器时间戳的对象附加到数组(字段类型)

Firestore onSnapshot 通过 onEffect 中的状态附加到数组

尝试将音乐项目附加到数组但超出范围错误(Swift)

为啥我不能将从 Firestore 获取的值分配给 Swift 中的数组?

你能用 swift 将字符串附加到 Firebase 数组吗

将数据从 Firestore 映射到 Swift 中的结构 - IOS