我正在为登录页面编写一些代码,我们在其中获取用户名并找到相关密码。暂时我已经说过“如果电子邮件存在于用户名下,则完成segue”。但是,当我调用检查电子邮件的方法getEmail时,似乎永远不会使用完整的电子邮件地址正确退出。 print(email)返回正确的电子邮件地址,所以我知道我已经检索到它并且它是正确的。我似乎从来没有通过这种方法。真的卡在这里!继承我的代码:
func getEmail(name: String) -> String{
var email = ""
ref = Database.database().reference()
self.ref.child("Users").child(name).observeSingleEvent(of: .value, with: { (snapshot) in
if let user = snapshot.value as? [String:Any] {
print("email retrieved");
email = user["email"] as! String;
print(email)
return;
}
else{
print("email could not be retrieved from the user.");
}
}){ (error) in
print("Could not retrieve object from database because: ");
print((Any).self);
}
return email;
}
func validate(){
if(Username.text == ""){
EmptyStringAlert();
}
let email = getEmail(name: Username.text!);
print(email)
if(email == ""){
return;
}
performSegue(withIdentifier: "LoginSuccess", sender: nil)
}
答案 0 :(得分:3)
对Firebase的调用是异步的,因此您必须在函数中使用completion来获取数据。尝试这样的事情:
func getEmail(name: String, completion: @escaping (Bool, Any?, Error?) -> Void) {
var email = ""
ref = Database.database().reference()
self.ref.child("Users").child(name).observeSingleEvent(of: .value, with: { (snapshot) in
if let user = snapshot.value as? [String:Any] {
email = user["email"] as! String
completion(true, email, nil)
}
else {
completion(false, nil, nil)
}
}){ (error) in
completion(false, nil, error)
}
}
func validate(){
if(Username.text == ""){
EmptyStringAlert();
}
getEmail(name: Username.text!) { (success, response, error) in
guard success, let email = response as? String else {
print(error ?? "Failed getEmail..")
return
}
if(email == "") {
return
}
performSegue(withIdentifier: "LoginSuccess", sender: nil)
}
}