简体   繁体   中英

Firebase Auth and Swift: Check if email already in database

I'm working on an iOS app which will use Firebase for user management (sign up, sign in, etc.)

I'm new to Firebase, but it's mostly going ok. I've connected it, I have created users and logged in, etc.

But, I'm trying to change my UI so that the "Sign up" button is initially hidden and will only appear when:

  1. all fields are not empty
  2. email address is valid (using regex)
  3. email address in not already in the database
  4. user name is not already in the database
  5. password and confirmPassword fields are equal

I can't figure out #3 and #4.

I've been reading documentation, watching videos, chasing links all over StackO and beyond, but I can't figure it out.

Can anyone point me in the right direction?

If you are using email & password authentication, the solution is very simple.

Firebase Authentication will not allow duplicate emails so when the createUser function is executed, if the email already exists Firebase will return a emailAlreadyInUse error in the error parameter. You can then cast this to an NSError to see which one it is and handle appropriately.

So the function is like this

Auth.auth().createUser(withEmail: createEmail, password: password ) { user, 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: //<- Your Error
         print("email is alreay in use")
      default:
         print("unknown error: \(err.localizedDescription)")
      }
      //return
   } else {
      //continue to app
   }

I threw some random errors into that case statement but check the link for a complete list of all AuthErrorCodes.

You can also do this

Auth.auth().fetchSignInMethods(forEmail: user, completion: { (signInMethods, error) in
    print(signInMethods)
})

I think you can check it by using this method

   let ref1 = Database.database().reference().child("Users").queryOrdered(byChild: "UserName").queryEqual(toValue: "UserName enter by user")

        ref1.observeSingleEvent(of: .value) { (sanpshot) in

            print(sanpshot.exists()) // it will return true or false
        }

and same for email.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM