簡體   English   中英

Firebase Auth和Swift:檢查數據庫中是否已存在電子郵件

[英]Firebase Auth and Swift: Check if email already in database

我正在使用iOS應用,該應用將使用Firebase進行用戶管理(注冊,登錄等)。

我是Firebase的新手,但是一切正常。 我已經連接好了,已經創建了用戶並登錄,等等。

但是,我正在嘗試更改UI,以使“注冊”按鈕最初處於隱藏狀態,並且僅在以下情況下顯示:

  1. 所有字段都不為空
  2. 電子郵件地址有效(使用正則表達式)
  3. 數據庫中尚未存在的電子郵件地址
  4. 用戶名尚未在數據庫中
  5. 密碼和ConfirmPassword字段相等

我不知道#3和#4。

我一直在閱讀文檔,觀看視頻,在StackO以及其他地方追蹤鏈接,但我不知道。

誰能指出我正確的方向?

如果您正在使用電子郵件和密碼身份驗證,則解決方案非常簡單。

Firebase身份驗證將不允許重復的電子郵件,因此,當執行createUser函數時,如果電子郵件已經存在,則Firebase會在error參數中返回emailAlreadyInUse錯誤。 然后可以將其強制轉換為NSError,以查看它是哪一個並進行適當處理。

所以功能是這樣的

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
   }

我在該case語句中添加了一些隨機錯誤,但請檢查鏈接以獲取所有AuthErrorCodes的完整列表。

您也可以這樣做

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

我認為您可以使用此方法進行檢查

   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
        }

與電子郵件相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM