【问题标题】:How to check if email already exists in Firestore db如何检查电子邮件是否已存在于 Firestore 数据库中
【发布时间】:2019-12-24 16:32:12
【问题描述】:

我已经为 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": Result!.user.uid - 线程 1:致命错误:在展开可选值时意外发现 nil。使用唯一电子邮件创建新用户时,它会正常工作,用户已创建。
  • 如果我将 if let document = document, document.exists 更改为 if error !=nil,我会在电子邮件已存在以及不存在时收到 UIAlert存在,创建用户的代码不执行。
  • 甚至尝试实现addsnapshotlistener,但没有成功。

有什么建议吗?谢谢

【问题讨论】:

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


    【解决方案1】:

    您可能不需要自定义函数来检查电子邮件是否已存在,因为这是默认错误 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 有一些更有用的信息,在答案代码中显示。

    【讨论】:

    • 感谢您的回答!这正是我想要的。
    【解决方案2】:

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

    另一个问题是因为您强制解开可以合法为 nil 的项目。

    相反,使用 guard 来隔离任何无效的情况并退出:

    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 ...
    

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 2019-09-17
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多