我具有以下提取功能。如何添加完成块,以便在完成时可以执行某些操作?
此查询将在内部多次运行代码。
func getFollowers() {
print("get followers called")
let ref = Database.database().reference()
ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
let personBeignFollow = snap.key
self.peopleUserFollows.append(personBeignFollow)
print("Appened: ", personBeignFollow)
self.fetchAllUserFirstPostMedia(user: personBeignFollow)
}
}
我看过here,但无法使其正常工作。
这是我尝试过的:
func getFollowers(_: ()-> ()) {
print("get followers called")
let ref = Database.database().reference()
ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
let personBeignFollow = snap.key
self.peopleUserFollows.append(personBeignFollow)
print("Appened: ", personBeignFollow)
self.fetchAllUserFirstPostMedia(user: personBeignFollow)
}
}
然后将其称为:
getFollowers() {
self.collectionView.reloadData()
}
答案 0 :(得分:0)
在函数声明中,可以添加以下内容:
func getFollowers(_ completion: @escaping () -> Void) {
print("get followers called")
let ref = Database.database().reference()
ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
let personBeignFollow = snap.key
self.peopleUserFollows.append(personBeignFollow)
print("Appened: ", personBeignFollow)
self.fetchAllUserFirstPostMedia(user: personBeignFollow)
// tell the calling function to execute the completion handler again
completion()
}
}
然后使用它,您将执行以下操作:
getFollowers {
// whatever you want to do after the query has run
}
这并不直接重要,但作为一种常见的设计实践,最好将从查询中检索到的新数据作为参数传递给完成处理程序,而不是在类上分配属性。< / p>
这看起来像这样:
func getFollowers(_ completion: (String) -> Void) {
ref.child("users2").child((Auth.auth().currentUser?.uid)!).child("Following").observe(.childAdded) { (snap) in
let personBeignFollow = snap.key
print("Appened: ", personBeignFollow)
// tell the calling function to execute the completion handler again
completion(personBeignFollow)
}
}
,然后您的呼叫站点可能如下所示:
getFollowers { newUser in
self.fetchAllUserFirstPostMedia(user: newUser)
}