2017-03-28 166 views
2

不知道這是一個錯誤還是一個預期的功能。Swift錯誤鑄造問題

要創建具有火力地堡的電子郵件和密碼的用戶,我一直在使用下面的代碼:

FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in 
    if let error = error { 
     guard let error = error as? FIRAuthErrorCode else { return } // ALWAYS FAILS 
     ...code... 
    } 
    ...code... 
} 

在不能被強制轉換爲FIRAuthErrorCode方法完成處理的故障參數;它總是失敗。這是一個錯誤,還是預期的行爲?

編輯:我知道錯誤代碼可以用來區分不同類型的FIRAuthErrorCode錯誤。這只是不可讀的,並且它對於完成處理程序中的錯誤參數不是FIRAuthErrorCode類型沒什麼意義。可以找到FIRAuthErrorCode的案例和錯誤代碼here

回答

0

在與Firebase支持部門聯繫後,他們表示在完成處理程序中傳回的錯誤僅爲Error對象。他們不是FIRAuthErrorCode對象。爲了測試各種FIRAuthErrorCode案件,人們必須做這樣的事情:

FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in 
    if let error = error { 
     guard let error = FIRAuthErrorCode(rawValue: error._code) else { 
      fatalError("This should never be executed") 
     } 
     switch error { 
     case .errorCodeInvalidEmail: ... 
     case .errorCodeWrongPassword: ... 
     default: ... 

     } 
     ...code... 
    } 
    ...code... 
} 

^這保留了可讀性,使錯誤處理更加直觀。而且,不需要錯誤轉換!

0

您是否嘗試過使用guard let error = error as! FIRAuthErrorCode else { return }來強制執行轉碼並檢查返回值是否爲零?

+1

您將無法編譯,因爲它會導致條件綁定錯誤。使用'as!'強制downcast總是返回一個非可選值,所以使用'guard let'沒有意義。但我確實測試過'let error = error as! FIRAuthErrorCode'之前,它產生了以下錯誤:'無法將類型'NSError'(0x1149070b8)的值轉換爲'__C.FIRAuthErrorCode'(0x104e35718)。' – hvasam

0

您應該檢查firebase中signIn方法的文檔,以檢查此方法可以發送的所有可能的錯誤類型,然後檢查代碼中guard塊中的錯誤類型。

+0

我已經這樣做了,但它需要使用錯誤代碼('FIRAuthErrorCode'中的各種情況的原始值)。我寧願使用錯誤代碼名稱('FIRAuthErrorCode.errorCodeEmailAlreadyInUse,FIRAuthErrorCode.errorCodeWrongPassword,等等)'。人們會認爲從'error'到'FIRAuthErrorCode'的轉換會起作用。 – hvasam

0

試試這個,這是我如何做我的登錄,它似乎很好。

FIRAuth.auth()?.signIn(withEmail: EmailField.text!, password: PasswordField.text!, completion: { user, error in 
     if error == nil { 
     print("Successfully Logged IN \(user!)") 
     self.performSegue(withIdentifier: "Login", sender: self) 
     } 
    }) 

我只是檢查有沒有與登入過程中出現錯誤,則執行我的SEGUE。

+0

我的現有代碼在沒有任何錯誤時運行良好。我沒有問題。這是我遇到的錯誤處理。我正在嘗試處理無效的密碼/電子郵件/等... – hvasam