Retrieving value from database

2019-03-02 18:53发布

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"

Have a nice day

1条回答
萌系小妹纸
2楼-- · 2019-03-02 19:00

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

And you call it like that:

getUserProfileMDP() { pass in
    print(pass)
    self.MDP = pass
}
查看更多
登录 后发表回答