Jonah Elbaz
Jonah Elbaz

Reputation: 325

Firebase observe method won't return and continue

I'm writing some code for a login page where we take a username and find the associated password. Temporarily I've said "if email exists under username, complete segue". However when I call the method getEmail which checks for email, it never seems to exit properly with a full email address. print(email) returns the right email address so I know I've retrieved it and it's correct. I never seem to make it out of the method though. Really stuck here! Heres my code:

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

Upvotes: 1

Views: 511

Answers (1)

nomadoda
nomadoda

Reputation: 4942

The call to Firebase is asynchronous, so you have to use completion in your function to get the data. Try something like this:

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

Upvotes: 3

Related Questions