【发布时间】:2020-06-30 18:06:07
【问题描述】:
我正在使用 Xcode 和 Swift 编程语言开发一个应用程序。请记住,我的应用与 Firebase 密切合作。我创建了一个函数来根据键从 Firebase 检索参数。
// My global variables. 'ref' is my firebase database and 'returnValue' is the value I am trying to write to withing the closure.
var ref = Database.database().reference(withPath: "accounts")
var returnValue: String = ""
func getParam(key: String) -> String {
let index = defs.integer(forKey: "index")
self.returnValue = "Failed retrieving parameter in getParam() function"
self.ref.child("data").observeSingleEvent(of: .value) { (snapshot) in
let data = snapshot.value! as! NSArray
let dictionary = data[index] as! NSDictionary
self.returnValue = String(describing: dictionary[key])
print("returnValue:", self.returnValue) //First line in console
return
}
return self.returnValue
}
override func viewDidLoad() {
super.viewDidLoad()
print(getParam("status")) //Second line in console
}
每当我调用此函数时,我都会在控制台中看到:
returnValue: Optional(0) //记住这是我在第二行中寻找的输出
在 getParam() 函数中检索参数失败
【问题讨论】:
-
这能回答你的问题吗? Returning data from async call in Swift function。您的调用是异步的,因此您的
print语句在从 firebase 下载数据之前执行(无论如何返回实例属性几乎没有意义)
标签: ios swift firebase firebase-realtime-database closures