ios - 在 iOS 13 上的 Swift 中设置 Sign in with Apple for Firebase 时出错的原因是什么?

标签 ios swift firebase sign-in-with-apple

我一直在关注https://firebase.google.com/docs/auth/ios/apple它确实提到了我收到的错误“将 SHA256 哈希随机数作为十六进制字符串发送”,但它没有提供任何帮助来解决它,而且我的搜索没有给我一个有效的解决方案。

我的 View Controller 代码摘录是


        fileprivate var currentNonce: String?

        @objc @available(iOS 13, *)
        func startSignInWithAppleFlow() {
          let nonce = randomNonceString()
          currentNonce = nonce
          let appleIDProvider = ASAuthorizationAppleIDProvider()
          let request = appleIDProvider.createRequest()
          request.requestedScopes = [.fullName, .email]
          request.nonce = sha256(nonce)
            print(request.nonce)

          let authorizationController = ASAuthorizationController(authorizationRequests: [request])
          authorizationController.delegate = self
          authorizationController.presentationContextProvider = self
          authorizationController.performRequests()
        }
        @available(iOS 13, *)
        private func sha256(_ input: String) -> String {
          let inputData = Data(input.utf8)
          let hashedData = SHA256.hash(data: inputData)
          let hashString = hashedData.compactMap {
            return String(format: "%02x", $0)
          }.joined()
            print(hashString)
          return hashString
        }
    }
    @available(iOS 13.0, *)
    extension LoginViewController: ASAuthorizationControllerDelegate {

      func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
          guard let nonce = currentNonce else {
            fatalError("Invalid state: A login callback was received, but no login request was sent.")
          }
          guard let appleIDToken = appleIDCredential.identityToken else {
            print("Unable to fetch identity token")
            return
          }
          guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
            print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
            return
          }
          // Initialize a Firebase credential.
            print(nonce)
            let credential = OAuthProvider.credential(withProviderID: "apple.com",
                                                      idToken: idTokenString,
                                                      accessToken: nonce)

            print(credential)
          // Sign in with Firebase.
          Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
            if (error != nil) {
              // Error. If error.code == .MissingOrInvalidNonce, make sure
              // you're sending the SHA256-hashed nonce as a hex string with
              // your request to Apple.
                print(authResult)
                print(error!)
                print(error!.localizedDescription)
              return
            }
            // User is signed in to Firebase with Apple.
            // ...
          }
        }
      }

这部分与网页上的说明不同,因为 Xcode 给出了错误


    let credential = OAuthProvider.credential(withProviderID: "apple.com",
                                                      idToken: idTokenString,
                                                      accessToken: nonce)

如果我之前打印随机数


    let credential = OAuthProvider.credential(withProviderID: "apple.com",
                                                      idToken: idTokenString,
                                                      accessToken: nonce)

我得到2eNjrtagc024_pd3wfnt_PZ0N89GZ_b6_QJ3IZ_

response.nonce值为cd402f047012a2d5c129382c56ef121b53a679c0a5c5e37433bcde2967225afe

显然这些不一样,但我似乎无法弄清楚我做错了什么。

完整的错误输出是

Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x60000388a820 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
    code = 400;
    errors =     (
                {
            domain = global;
            message = "MISSING_OR_INVALID_NONCE : Nonce is missing in the request.";
            reason = invalid;
        }
    );
    message = "MISSING_OR_INVALID_NONCE : Nonce is missing in the request.";
}}}, FIRAuthErrorUserInfoNameKey=ERROR_INTERNAL_ERROR, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
An internal error has occurred, print and inspect the error details for more information.

最佳答案

我遇到了同样的错误。

解决方案: 运行即可

pod 更新

说明:

问题正如@ethanrj 所说。文档说要做

let credential = OAuthProvider.credential( 
    withProviderID: "apple.com", IDToken: appleIdToken, rawNonce: rawNonce )

但这会产生错误,Xcode 将建议以下内容(rawNonce -> accessToken):

let credential = OAuthProvider.credential( 
    withProviderID: "apple.com", IDToken: appleIdToken, accessToken: rawNonce )

这是因为 pod install 默认情况下会安装 FirebaseAuth 6.12,而您确实需要 6.13,因为新函数签名仅在此处可用。可以查看源码here .

关于ios - 在 iOS 13 上的 Swift 中设置 Sign in with Apple for Firebase 时出错的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011314/

相关文章:

iphone - 如何在 iOS 中点击时突出显示自定义 UIButton

ios - 我可以显示全屏 ViewController,但仍然可以向下滑动以返回父级(启动器)ViewController

ios - 获取 SKPhysicsBody 以在纹理动画时更新 (Swift)

Swift WatchOS 错误 : Unknown property in Interface description ('image' ) for controller

ios - Firebase 动态链接在 safari swift 中不起作用

javascript - 如何查看表中的 firebase 对象

Android 应用程序到 IOs 移植?

ios - 如何在 iTunes connect 中本地化阿拉伯语应用程序?

ios - 使用 encodable-decodable 从 api 中的数组解析

Java if- else 字符串.contains 不起作用错误