[英]How can i access variables inside of firebase .ref closures and use them outside
我在firebase函数中声明了一个变量,我想在函数外部使用它。 我已经在函数外部声明了变量,然后在firebase函数内部设置了变量,但是我仍然无法检索到该如何处理。
let ref = firebasehelper.firebaseURL()
var userDict = [String:String]()
var name:String!
override func viewDidLoad() {
super.viewDidLoad()
ref.childByAppendingPath("backend/posts").queryOrderedByChild("jobOfferFromId").queryEqualToValue(ref.authData.uid).observeEventType(.ChildAdded, withBlock: {snapshot in
self.name = snapshot.value["jobDescribe"] as! String
// work greate in here
print(self.name)
})
// does not work outside of the Firebase function I want to access the data out here
print(self.name)
}
那是因为您在从Firebase取回数据之前先执行print(self.name)。
您可以将查询放入viewWillAppear中,然后在viewDidAppear或viewDidLoad中执行print(self.name)。 最好的方法是实际使用闭包,并且仅在返回数据后才触发下一步(打印),因此可以通过引用函数(使用print(self.name)或对数据的其他使用)来实现在viewDidLoad外部。
在类中创建一个func
,然后将该func
放在类中,这将允许您在函子中设置该变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.