简体   繁体   English

我如何在firebase .ref闭包内部访问变量并在外部使用它们

[英]How can i access variables inside of firebase .ref closures and use them outside

I declared a variable inside a firebase function i would like to use it outside of the function. 我在firebase函数中声明了一个变量,我想在函数外部使用它。 I already declare the variable outside of the function and then set it inside of the firebase function but Im still not able to retrieve how can i process this. 我已经在函数外部声明了变量,然后在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)

}

that is because you do the print(self.name) before you have the data back from Firebase. 那是因为您在从Firebase取回数据之前先执行print(self.name)。

You could put the query in viewWillAppear and then do the print(self.name) in viewDidAppear or viewDidLoad. 您可以将查询放入viewWillAppear中,然后在viewDidAppear或viewDidLoad中执行print(self.name)。 best would be to actually use the closure and only trigger the next step (print) once the data is back, so by putting a reference to a function (with the print(self.name) or any other use you have for the data) outside viewDidLoad. 最好的方法是实际使用闭包,并且仅在返回数据后才触发下一步(打印),因此可以通过引用函数(使用print(self.name)或对数据的其他使用)来实现在viewDidLoad外部。

在类中创建一个func ,然后将该func放在类中,这将允许您在函子中设置该变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM