gpt4 book ai didi

Swift:如何为从 Firebase 数据库获取数据的函数实现完成处理程序

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

我已经编写了代码来从我的 Firebase 数据库检索数据并将其附加到名为 toWatchMoviesListInitial 的数组中。但是,在打印出 toWatchMoviesListInitial 的值后附加数据后,它什么也不打印。
有人告诉我这是因为这是异步的。为了处理这个问题,可以使用完成处理程序。
但是,我是 swift 的新手,我不知道如何实现完成处理程序。如果您能告诉我如何去做,我将不胜感激。这是我的代码:

func initialiseTicketsList() {
ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
ref?.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let userDict = dictionary["watchList"] as? [String:String]
for (_,myValue) in userDict! {
if myValue.contains("ignore"){
}
else{
print(type(of: myValue))
self.toWatchMoviesListInitial.append(myValue)
}
}
}
}, withCancel: nil)

print(toWatchMoviesList) //prints empty when it shouldn't
}

最佳答案

func initialiseTicketsList(completionHandler: @escaping ([String]) -> Void) {
ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
ref?.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let userDict = dictionary["watchList"] as? [String:String]
var toWatchMoviesListInitial: [String] = [] //local variable
for (_,myValue) in userDict! {
if myValue.contains("ignore"){
}
else{
print(type(of: myValue))
toWatchMoviesListInitial.append(myValue)
}
}
completionHandler(toWatchMoviesListInitial) // callback invoked.
}
}, withCancel: nil)
}

// wherever you call initialiseTicketsList, call with completionHandler
initialiseTicketsList(completionHandler: {movieList in
self.toWatchMoviesList = movieList // or append based on your usecase.
}

请阅读 here 上有关 closure@escaping 的内容

关于Swift:如何为从 Firebase 数据库获取数据的函数实现完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458848/

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