2017-05-08 7 views
0

firebaseに接続して特定のパスに移動してから値を返す関数を作った。私が印刷すると(snapshot.value)、それは私に必要な値を与えます。関数を呼び出すと、userProfileは空です。スナップショット文字列を返すにはuserProfileが必要です。Return Statement SwiftのFirebaseを使用したときのエラー

func getUserData(uid: String) -> String{ 
    var _REF_USERNAME = FIRDatabase.database().reference().child("users").child(uid).child("profile").child("username") 

    var userProfile = String() 


    _REF_USERNAME.observe(.value, with: {(snapshot) in 
     print("SNAP: \(snapshot.value)") 
      userProfile = snapshot.value as! String 

    }) 
    print(userProfile) 
    return userProfile 
} 
+1

Firebaseからデータが返される前にリターンが実行されています。 Firebaseのデータは、クロージャ内でのみ有効になります。私の答えは[この質問](http://stackoverflow.com/questions/43823808/access-firebase-variable-outside-closure/43832208#43832208)と[this one](http://stackoverflow.com)をご覧ください。/questions/43130730/table-view-is-not-displayed-fire-usernameからfire-base-43157576#43157576)を参照してください。通常、Firebase関数からの戻りデータは非同期であるため、コードの残りの部分は同期している必要があります。 – Jay

答えて

2

それは観測機能の前に実行されますので、あなたは、観察中のコールバックの外にUSERPROFILEを呼び出しているスウィフト3

は非同期で完了します。コールバックは最初は理解しにくいですが、一般的な考え方はコードが上から順に実行されず、バックグラウンドスレッドで非同期に実行されるコードの部分がいくつかあることです。

USERPROFILEへのアクセスを取得するには、ちょうどそのようにコールバック関数に渡す必要があります:

func observeUserProfile(completed: @escaping (_ userProfile: String?) ->()) -> (FIRDatabaseReference, FIRDatabaseHandle) { 

    let ref = _REF_USERNAME 

    let handle = ref.observe(.value, with: {(snapshot) in 
      if !snapshot.exists() { // First check if userProfile exists to be safe 
       completed(nil) 
       return 
      } 
      userProfile = snapshot.value as! String 
      // Return userProfile here in the callback 
      completed(userProfile) 
    }) 
    // Good practice to return ref and handle to remove the handle later and save memory 
    return ref, handle 

そして、あなたは、このようなコールバック関数に渡しながら、外のコードを観察呼び出す:

let ref, handle = observeUserProfile(completed: { (userProfile) in 
    // Get access to userProfile here 
    userProfile 
} 

そして、このオブザーバーが終了したら、以下を実行して観察を止め、メモリーを節約してください。

ref.removeObserver(withHandle: handle) 
関連する問題