Как проверить правильность входа пользователя в приложение Firebase Swift? - PullRequest
0 голосов
/ 25 февраля 2020

У меня проблема, даже когда я ввел неправильный пароль, мое приложение показывало мне информацию об успешном входе в систему, но на самом деле это не так. Как заставить его работать правильно?

Auth.auth().fetchSignInMethods(forEmail: userEmail, completion: {
            (providers, error) in

            if error != nil {
                self.displayAlertMessage(alertTitle: "Unhandled error", alertMessage: "Undefined error #SignUpViewController_0001");
                return;
            } else if providers == nil {
                self.displayAlertMessage(alertTitle: "Error", alertMessage: "This account is not exist.");
                return;
            }
        })

        // Login

        Auth.auth().signIn(withEmail: userEmail, password: userPassword) { [weak self] authResult, error in
            guard self != nil else {
                self?.displayAlertMessage(alertTitle: "Alert", alertMessage: "Wrong password.");
                return }
        }

        self.displayAlertMessage(alertTitle: "Success", alertMessage: "You are successfuly sign in.", dismiss: true);

        // Return to initial view

Ответы [ 3 ]

0 голосов
/ 25 февраля 2020

Эта функция, которую я написал для моего текущего приложения.

func loginButtonTapped() {
    indicator.setupIndicatorView(view, containerColor: .white, indicatorColor: .CustomGreen())
    view.alpha = 0.7
    let email = mainView.userEmail
    let password = mainView.userPassword
    Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
        if error == nil {
            if Auth.auth().currentUser?.isEmailVerified == true {
                self.view.alpha = 1.0
                self.indicator.hideIndicatorView()
                print("Logined")
            } else {
                Auth.auth().currentUser?.sendEmailVerification(completion: { (error) in
                    if error == nil {
                        self.view.alpha = 1.0
                        self.indicator.hideIndicatorView()
                        Alert.showAlert(title: "Warning", subtitle: "You have not activate your account yet. We have sent you an email to activate it.", leftView: UIImageView(image: #imageLiteral(resourceName: "isWarningIcon")), style: .warning)
                    } else {
                        self.view.alpha = 1.0
                        self.indicator.hideIndicatorView()
                        Alert.showAlert(title: "Error", subtitle: "Incorrect email.", leftView: UIImageView(image: #imageLiteral(resourceName: "isErrorIcon")), style: .danger)
                    }
                })
            }
        } else {
            self.view.alpha = 1.0
            self.indicator.hideIndicatorView()
            Alert.showAlert(title: "Error", subtitle: "Incorrect email or password.", leftView: UIImageView(assetIdentifier: AssetIdentifier.error)!, style: .danger)
        }
    }
}
0 голосов
/ 26 февраля 2020

Как упоминал Дуг в своем ответе, Firebase является асинхронным, и данные действительны только в замыкании после вызова функции. Чтобы эти данные стали действительными, требуется время, поэтому любой код вне вызова функции после замыкания будет вызываться до того, как код внутри замыкания.

Так что это означает для твоего кода

Auth.auth().signIn(withEmail: userEmail, password: userPassword) { [weak self] authResult, error in
     //this code will execute *after* the code that displays success
}

//this code will execute *before* the code within the closure following the signIn 
self.displayAlertMessage(alertTitle: "Success"

Вот пример кода, который обрабатывает ошибки и обеспечивает правильную последовательность для потока кода.

Auth.auth().signIn(withEmail: user, password: pw, completion: { (auth, error) in
    if let x = error {
        let err = x as NSError
        switch err.code {
        case AuthErrorCode.wrongPassword.rawValue:
            print("wrong password")
        case AuthErrorCode.invalidEmail.rawValue:
            print("invalued email")
        case AuthErrorCode.accountExistsWithDifferentCredential.rawValue:
            print("accountExistsWithDifferentCredential")
        default:
            print("unknown error: \(err.localizedDescription)")
        }
    } else {
        if let _ = auth?.user {
            print("authd") //user is auth'd proceed to next step
        } else {
            print("authentication failed - no auth'd user")
        }
    }
})
0 голосов
/ 25 февраля 2020

Auth.auth().signIn() является асинхронным и возвращается немедленно. Пройденный вами обратный вызов будет вызван через некоторое время с результатами входа. Ваш код выполняет немедленный вызов self.displayAlertMessage(alertTitle: "Success",...) до завершения входа. Вы должны ожидать результатов входа только в обратном вызове, а не в следующей строке кода после вызова signIn().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...