Auth.auth (). CurrentUser? .Uid = nil iOS Firebase - PullRequest
0 голосов
/ 04 октября 2018

Установка переменной в значение Auth.auth().currentUser?.uid всегда возвращает nil даже после того, как пользователь вошел в систему, я упускаю тот факт, что Firebase иногда использует асинхронные методы?Функция, используемая для возврата данных из базы данных Firebase в реальном времени, запускается после функции входа в систему и в настоящее время использует постоянный UID для целей тестирования.

typealias RetrieveUserCompletionBlock = ((_ userType: String) -> Void)
func retrieveUserType(withBlock completion: @escaping RetrieveUserCompletionBlock){

    let userTypeDB = Database.database().reference()
    let currentUser = "kLxqZteRfBeC0bNIkLCjrPukMGx1"

    var testUser = Auth.auth().currentUser?.uid
    print(testUser)

    userTypeDB.child("UserType").child(currentUser).observeSingleEvent(of: .value, with: {
        (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let email = value?["Email"] as? String ?? ""
        completion(value?["User Type"] as? String ?? "")
    }){
        (error) in
        completion("default value")
        print(error.localizedDescription)
    }
}

@IBAction func loginButtonPressed(_ sender: Any) {

    SVProgressHUD.show()

    Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in

        if error != nil {
            //error
            if let errorCode = AuthErrorCode(rawValue: error!._code) {

                switch errorCode {

                case .missingEmail:
                    SVProgressHUD.showError(withStatus: "Please enter a email in the text field")
                    SVProgressHUD.dismiss(withDelay: 2)
                case .userDisabled:
                    SVProgressHUD.showError(withStatus: "Your account is disabled")
                    SVProgressHUD.dismiss(withDelay: 2)
                case .invalidEmail:
                    SVProgressHUD.showError(withStatus: "Invalid email, please enter a valid email")
                    SVProgressHUD.dismiss(withDelay: 2)
                case .wrongPassword:
                    SVProgressHUD.showError(withStatus: "Incorrect password")
                    SVProgressHUD.dismiss(withDelay: 2)
                case .userNotFound:
                    SVProgressHUD.showError(withStatus: "Account details not found, please try again")
                    SVProgressHUD.dismiss(withDelay: 2)
                default:
                    print("Error")
                }
            }
        }

        else {
            //success
            SVProgressHUD.showSuccess(withStatus: "Success")
            SVProgressHUD.dismiss(withDelay: 1)
            self.performSegue(withIdentifier: "goToMenuFromLogin", sender: self)
        }
    }
    retrieveUserType { (userType) in
        if userType != "Student"{
            print("error")
        } else {
            print("success")
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...