gpt4 book ai didi

ios - 如何将完成 block 添加到 .childAdded firebase 查询?

转载 作者:行者123 更新时间:2023-11-28 07:29:01 25 4
gpt4 key购买 nike

我有以下获取功能。我如何添加一个完成 block 以便在它完成时我可以做一些事情?

这个查询会多次运行里面的代码。

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

最佳答案

在您的函数声明中,您可以添加以下内容:

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
}

这并不直接重要,但作为一种常见的设计实践,最好将您从查询中检索到的新数据作为完成处理程序中的参数传递,而不是在类上分配属性。

看起来像这样:

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

关于ios - 如何将完成 block 添加到 .childAdded firebase 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55584367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com