2016-09-14 3 views
0

私は、UserProfileノードからダッシュボードからいくつかの値を取得し、それらをグローバル変数に渡してobserve関数の外でグローバルに使用しようとしています。取得したノードの値を取得し、それらをグローバルに使用する! (FirebaseとSwift)

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) 
     } 
    }) 

observe関数の外に渡したいので、.swiftファイルのどこにでもそれらを使用できます。

答えて

2

Firebase関数はであるため、非同期では、関数のcompletionBlock内でこれらのユーザープロパティにアクセスする必要があります。そして、彼らは呼び出しが完了した後にのみ検索値を与えることを心に留めておいてください。

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) 
    } 
}) 

} 
関連する問題