如何检查Firestore数据库中是否已存在电子邮件

时间:2019-12-24 16:32:12

标签: swift firebase authentication google-cloud-firestore firebase-authentication

我已经为 Firestore 数据库实现了Auth方法,但是当用户尝试使用同一封电子邮件注册时,应用程序崩溃。我想实现一个功能来检查电子邮件是否已经存在(如果存在,请启动UIAlert,否则,请创建一个新用户)。

我到目前为止:

Auth.auth().createUser(withEmail: email, password: password) { (Result, err) in

let db = Firestore.firestore()
            let docRef = db.collection("email users").document("email")
            docRef.getDocument { (document, error) in
                if let document = document, document.exists {

                    let emailAlreadyInUseAlert = UIAlertController(title: "Error", message: "Email already registered", preferredStyle: .alert)
                    emailAlreadyInUseAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    self.present(emailAlreadyInUseAlert, animated: true, completion: nil)

                    return
                } else {
                    let db = Firestore.firestore()
                    db.collection("email users").addDocument(data: [
                                                    "firstName": firstName,
                                                    "lastName": lastName,
                                                    "email": email,
                                                    "created": Timestamp(date: Date()),
                                                    "uid": Result!.user.uid
                                                ])

                            }
                            self.transitionToHome()

                    }


                    }
                }
            }


func transitionToHome() {

    let homeViewController = storyboard?.instantiateViewController(identifier: "HomeViewController") as? HomeViewController

    view.window?.rootViewController = homeViewController
    view.window?.makeKeyAndVisible()

   }
}
  • 在此代码中,UIAlert不会触发,并在以下位置出现错误:“ uid”:结果!.user.uid-线程1:致命错误:在展开可选值时意外发现nil 。使用唯一的电子邮件创建新用户时,它可以正常工作,并创建了该用户。
  • 如果我将 if document = document,document.exists 更改为 if error!= nil ,则当电子邮件已经存在以及是否不存在时,我都会收到UIAlert存在,创建用户的代码不会执行。
  • 即使尝试实现addsnapshotlistener,也没有运气。

有什么建议吗?谢谢

2 个答案:

答案 0 :(得分:1)

关于错误:返回成功代码作为错误代码而不是将error设置为nil是一种常见的做法,而Google文档似乎是mention it as well

另一个问题是因为您正在强行展开可以合法为零的项目。

相反,请使用警卫来隔离所有无效案例并退出:

guard error == nil || case FirestoreErrorCode.OK = error else {
    // got error; process it and 
    return
}

guard let result = result else {
    // got no error, but no result either
    // fail and
    return
}

//if you are here, it means you've got no error and `result` is not nil.

还要注意,result不应在回调中大写:

Auth.auth().createUser(withEmail: email, password: password) { (result, err) in ...

答案 1 :(得分:0)

您可能不需要自定义功能来检查电子邮件是否已存在,因为这是Firebase Auth会捕获并允许您在创建用户时处理的默认错误。

例如,此代码将捕获用户尝试使用已经存在的电子邮件的情况。

func createUser() {
    let email = "test@thing.com"
    Auth.auth().createUser(withEmail: email, password: "password", completion: { authResult, 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("invalid email")
            case AuthErrorCode.accountExistsWithDifferentCredential.rawValue:
                print("accountExistsWithDifferentCredential")
            case AuthErrorCode.emailAlreadyInUse.rawValue:
                print("email already in use")
            default:
                print("unknown error: \(err.localizedDescription)")
            }
            return
        }

        let x = authResult?.user.uid
        print("successfully created user:  \(x)")
    })
}

有许多Authentication Error Codes,因此您可以处理各种错误,而无需任何特殊的错误处理。

AuthErrorCode API还有一些更有用的信息,在答案代码中得到了证明。

相关问题