嗨,我有一个问题,并会感激任何建议或答案。
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 :(得分: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
}