从数据库中检索值 [英] Retrieving value from database

查看:106
本文介绍了从数据库中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,感谢您的任何建议或答案.

Hi I have a problem and would be grateful to any advice or answer.

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

这是从数据库获取值的函数.可行(第一个打印得到正确的值)

Here is the function that gets the value from database. It works (the first print gets the right value)

    @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

那是我需要密码才能进行比较.它不能获取数据库的值,但是可以在上面的类中初始化该值:

That is were I need the password to compare it. It doesn't get me the value of the database but the value initialized in class above:

var MDP = "nope"

祝你有美好的一天

推荐答案

给出您的最后评论,我想说您快到了,但这是一个示例.我没有修复代码的其他部分,仅在方法签名中添加了完成处理程序,并将密码值传递给该处理程序,以向您展示其工作原理.必须在异步闭包内部调用该处理程序.

Given your last comment, I'd say that you're almost there, but here's an example. I did not fix the other parts of your code, I only added the completion handler in the method signature, and passed the password value to the handler, to show you how this works. The handler must be called inside the async closure.

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
}

这篇关于从数据库中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆