2017-09-01 143 views
1

嗨我有一個問題,並會感謝任何意見或答案。從數據庫檢索值

func getUserProfileMDP(){ 

    // set attributes to textField 
    var ref: DatabaseReference! 
    ref = Database.database().reference() 
    let user = Auth.auth().currentUser 
    print(user!.uid) 
    ref.child("users").child((user?.uid)!).observeSingleEvent(of: .value, with: { (snapshot) in 
     // Get user value 
     guard let value = snapshot.value as? [String: String] else { return } 
     print(value) 
     let passwordValue = value["password"]!as! String 
     print(passwordValue) 
     self.MDP = passwordValue // prints the right value from database 

    }){ (error) in 
     print(error.localizedDescription) 
    } 
    print(self.MDP) // prints the value innitialised in class(nope) 
} 

這裏是從數據庫中獲取值的函數。它的工作原理(第一個打印得到正確的值)

@IBAction func register(_ sender: Any) { 

    print(self.MDP)// prints the value innitialised in class(nope) 
    getUserProfileMDP() 
    print(self.MDP) // prints the value innitialised in class(nope) 
    let MDP = self.MDP 

那是我需要密碼來比較它。它不會讓我的數據庫的初始化類以上的價值,但價值:

var MDP = "nope" 

有一個愉快的一天

+0

因爲'.observeSingleEvent'在'getUserProfileMDP()'是異步的。所以程序控制流程不是你想象的那樣。使用回撥! – Moritz

+0

我是新來的swift你能準確地知道什麼是「回調」? –

回答

2

鑑於你最後的評論,我會說,你幾乎沒有,但是這裏有一個例子。我沒有修復代碼的其他部分,我只在方法簽名中添加了完成處理程序,並將密碼值傳遞給處理程序,以向您展示這是如何工作的。處理程序必須在異步閉包內部調用。

func getUserProfileMDP(completion: @escaping (String)->()) { 
    // set attributes to textField 
    var ref: DatabaseReference! 
    ref = Database.database().reference() 
    let user = Auth.auth().currentUser 
    print(user!.uid) 
    ref.child("users").child((user?.uid)!).observeSingleEvent(of: .value, with: { (snapshot) in 
     // Get user value 
     guard let value = snapshot.value as? [String: String] else { return } 
     print(value) 
     let passwordValue = value["password"]!as! String 

     completion(passwordValue) 

    }){ (error) in 
     print(error.localizedDescription) 
    } 
} 

而且你怎麼稱呼它那樣:

getUserProfileMDP() { pass in 
    print(pass) 
    self.MDP = pass 
} 
+0

對不起,麻煩理解這個語法,調用getUserProfileMDP就像你在我的@IBAction中寫的那樣沒有解決,打印仍然是MDP初始化類 –

+0

print(self.MDP)應該在裏面'{pass in ...}',而不是之後。 – Moritz