Mariah Mariah - 5 months ago 48
Swift Question

Get the Values of the Retrieved Nodes and Use them Globally! (Firebase and Swift)

I'm trying to get some values from the UserProfile node from the dashboard and pass them into global variables to use them globally outside the observe function.

ref.child("UserProfile").child(FIRAuth.auth()!.currentUser!.uid).observeEventType(.Value , withBlock: {snapshot in
if let name = snapshot.value!.objectForKey("name") as? String {
if let email = snapshot.value!.objectForKey("email") as? String {
if let phone = snapshot.value!.objectForKey("phone") as? String {
if let city = snapshot.value!.objectForKey("city") as? String {

I want to pass them outside the observe function so I can use them globally anywhere in the .swift file.


Since Firebase functions are supposed to be Asynchronous, you need to access these User properties inside the completionBlock of the function. And mind that They will only give retrieved value once the call has been completed.

var globalUserName : String!
var globalEmail : String!
var globalPhone : String!
var globalCity : String!

 override func viewWillAppear(animated : Bool){
        retrieveUserData{(name,email,phone,city) in
            self.globalUserName = name
            self.globalEmail = email
            self.globalPhone = phone
            self.globalCity = city


 func retrieveUserData(completionBlock : ((name : String!,email : String!, phone : String!, city : String!)->Void)){
   ref.child("UserProfile").child(FIRAuth.auth()!.currentUser!.uid).observeEventType(.Value , withBlock: {snapshot in

     if let userDict =  snapshot.value as? [String:AnyObject]  {

          completionBlock(name : userDict["name"] as! String,email : userDict["email"] as! String, phone : userDict["phone"] as! String, city : userDict["city"] as! String)