0

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 {
        print(name)
        }
        if let email =  snapshot.value!.objectForKey("email") as? String {
        print(email)
        }
        if let phone =  snapshot.value!.objectForKey("phone") as? String {
        print(phone)
        }
        if let city =  snapshot.value!.objectForKey("city") as? String {
        print(city)
        }
    })

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

Mariah
  • 573
  • 3
  • 10
  • 26

1 Answers1

2

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){
     super.viewWillAppear(animated)
        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)
    }
 })

}
Dravidian
  • 9,945
  • 3
  • 34
  • 74