2017-09-01 135 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