ios - Firebase google登录身份验证AppDelegate-使用未解析的标识符 'isMFAEnabled'

标签 ios swift firebase-authentication google-signin appdelegate

我是 iOS 开发的新手。我正在尝试将谷歌登录添加到我的应用程序中,但我遇到了一些问题。代码显示一些“使用未解析的标识符'isMFAEnabled”和“'AppDelegate' 类型的值没有成员'showTextInputPrompt'”。请帮助我。我正在关注这个文档- https://firebase.google.com/docs/auth/ios/google-signin#swift_9 enter image description here

import UIKit
import Firebase
import GoogleSignIn

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate {
   
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url)
    }
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
           if let error = error {
            print(error.localizedDescription)
             return
           }

           guard let authentication = user.authentication else { return }
           let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                             accessToken: authentication.accessToken)
          Auth.auth().signIn(with: credential) { (authResult, error) in
            if let error = error {
              let authError = error as NSError
              if (isMFAEnabled && authError.code == AuthErrorCode.secondFactorRequired.rawValue) {
                // The user is a multi-factor user. Second factor challenge is required.
                let resolver = authError.userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver
                var displayNameString = ""
                for tmpFactorInfo in (resolver.hints) {
                  displayNameString += tmpFactorInfo.displayName ?? ""
                  displayNameString += " "
                }
                self.showTextInputPrompt(withMessage: "Select factor to sign in\n\(displayNameString)", completionBlock: { userPressedOK, displayName in
                  var selectedHint: PhoneMultiFactorInfo?
                  for tmpFactorInfo in resolver.hints {
                    if (displayName == tmpFactorInfo.displayName) {
                      selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo
                    }
                  }
                  PhoneAuthProvider.provider().verifyPhoneNumber(with: selectedHint!, uiDelegate: nil, multiFactorSession: resolver.session) { verificationID, error in
                    if error != nil {
                      print("Multi factor start sign in failed. Error: \(error.debugDescription)")
                    } else {
                      self.showTextInputPrompt(withMessage: "Verification code for \(selectedHint?.displayName ?? "")", completionBlock: { userPressedOK, verificationCode in
                        let credential: PhoneAuthCredential? = PhoneAuthProvider.provider().credential(withVerificationID: verificationID!, verificationCode: verificationCode!)
                        let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator.assertion(with: credential!)
                        resolver.resolveSignIn(with: assertion!) { authResult, error in
                          if error != nil {
                            print("Multi factor finanlize sign in failed. Error: \(error.debugDescription)")
                          } else {
                            self.navigationController?.popViewController(animated: true)
                          }
                        }
                      })
                    }
                  }
                })
              } else {
                print(error.localizedDescription)
                return
              }
              // ...
              return
            }
            // User is signed in
            // ...
          }
       }
    
    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
          let firebaseAuth = Auth.auth()
        do {
          try firebaseAuth.signOut()
        } catch let signOutError as NSError {
          print ("Error signing out: %@", signOutError)
        }

最佳答案

所以样板代码比你需要的要多。这是我对您的 AppDelegate 的评论。

  • didFinishLaunchingWithOptions 看起来不错。
    专业提示:添加此行以保持登录 GIDSignIn.sharedInstance()?.restorePreviousSignIn()
  • 打开,选项 看起来不错。
  • didSignInFor 用户 是它纠结的地方。删除整个函数并将其替换为以下扩展名(在类的括号外):

  • (同时在类协议(protocol)中删除 GIDSignInDelegate)
        extension AppDelegate: GIDSignInDelegate {
        func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
            
            //handle sign-in errors
            if let error = error {
                if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
                    print("The user has not signed in before or they have since signed out.")
                } else {
                print("error signing into Google \(error.localizedDescription)")
                }
            return
            }
            
            // Get credential object using Google ID token and Google access token
            guard let authentication = user.authentication else { return }
            
            let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                            accessToken: authentication.accessToken)
            
            // Authenticate with Firebase using the credential object
            Auth.auth().signIn(with: credential) { (authResult, error) in
                if let error = error {
                    print("authentication error \(error.localizedDescription)")
                }
            }
        } 
    }
    
    我今天已经对此进行了测试,它目前正在运行(Swift 5/ios 13.6)。

    关于ios - Firebase google登录身份验证AppDelegate-使用未解析的标识符 'isMFAEnabled',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62624288/

    相关文章:

    ios - 在 ARC 中释放强引用

    ios - 如何为 watch 套件应用播放声音

    javascript - Firebase 如何比较数据规则中的变量(== vs ===)?

    java - 为什么登录 Facebook 帐户时用户电子邮件为空,但登录 Google 帐户时不为空?

    ios - 如何向 google Direction api 发送请求以快速获取路径

    ios - iPad 引导访问

    arrays - 当 Int 值为 0 时从数组(tableView)中删除

    ios - 在哪里最好使用 Watch Connectivity 调用 updateApplicationContext?

    ios - 在 iOS 中开始在 TextField 中输入时,PlaceHolder 会显示动画

    android - Firebase 电子邮件验证链接中的深层链接不起作用