Google Sign In & Firebase with SwiftUI

huangapple go评论57阅读模式
英文:

Google Sign In & Firebase with SwiftUI

问题

嗨,我在尝试在一个SwiftUI项目中使用Google和Firebase的登录。现在我在检查旧的实现方法以及一些从网络上得到的建议时遇到了代码的问题。

guard let authentication = user?.authentication, let idToken = authentication.idToken else { return }

出错了,错误是Value of type 'GIDGoogleUser' has no member 'autentication'。我知道Google更改了一些属性,用新的替代了旧的。在SwiftUI中,我该如何更新Google登录的实现呢?

英文:

Hi all I was trying to use sign in with google and firebase in a SwiftUI project. Now checking the old implementation methods and also some suggestions got from the net I am having problem with this part of the code

private func authenticateUser(for user: GIDGoogleUser?, with error: Error?) {
  // 1
  if let error = error {
    print(error.localizedDescription)
    return
  }
  
  // 2
  guard let authentication = user?.authentication, let idToken = authentication.idToken else { return }
  
  let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken)
  
  // 3
  Auth.auth().signIn(with: credential) { [unowned self] (_, error) in
    if let error = error {
      print(error.localizedDescription)
    } else {
      self.state = .signedIn
    }
  }
}

I'm getting errors with this authentication constant

  guard let authentication = user?.authentication, let idToken = authentication.idToken else { return }

The error is Value of type 'GIDGoogleUser' has no member 'autentication'


i know google dropped some properties replacing them...currently how can i update the google login implementation in SwiftUI?

答案1

得分: 2

这是如何在使用最新版本(7.0.0)的Google Sign-In SDK时,对Firebase用户进行身份验证的方法:

extension AuthenticationViewModel {
  func signInWithGoogle() async -> Bool {
    guard let clientID = FirebaseApp.app()?.options.clientID else {
      fatalError("在Firebase配置中找不到客户端ID")
    }
    let config = GIDConfiguration(clientID: clientID)
    GIDSignIn.sharedInstance.configuration = config

    guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
          let window = windowScene.windows.first,
          let rootViewController = window.rootViewController else {
      print("没有根视图控制器!")
      return false
    }

      do {
        let userAuthentication = try await GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController)

        let user = userAuthentication.user
        guard let idToken = user.idToken else { throw AuthenticationError.tokenError(message: "缺少ID令牌") }
        let accessToken = user.accessToken

        let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString,
                                                       accessToken: accessToken.tokenString)

        let result = try await Auth.auth().signIn(with: credential)
        let firebaseUser = result.user
        print("用户 \(firebaseUser.uid) 使用电子邮件 \(firebaseUser.email ?? "unknown") 登录")
        return true
      }
      catch {
        print(error.localizedDescription)
        self.errorMessage = error.localizedDescription
        return false
      }
  }
}

查看在Apple平台上开始使用Google Sign-In - YouTube,其中我详细解释了配置选项。

英文:

Here is how you can authenticate a Firebase user when using Google Sign-In using the latest release (7.0.0) of the Google Sign-In SDK:

extension AuthenticationViewModel {
  func signInWithGoogle() async -> Bool {
    guard let clientID = FirebaseApp.app()?.options.clientID else {
      fatalError("No client ID found in Firebase configuration")
    }
    let config = GIDConfiguration(clientID: clientID)
    GIDSignIn.sharedInstance.configuration = config

    guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
          let window = windowScene.windows.first,
          let rootViewController = window.rootViewController else {
      print("There is no root view controller!")
      return false
    }

      do {
        let userAuthentication = try await GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController)

        let user = userAuthentication.user
        guard let idToken = user.idToken else { throw AuthenticationError.tokenError(message: "ID token missing") }
        let accessToken = user.accessToken

        let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString,
                                                       accessToken: accessToken.tokenString)

        let result = try await Auth.auth().signIn(with: credential)
        let firebaseUser = result.user
        print("User \(firebaseUser.uid) signed in with email \(firebaseUser.email ?? "unknown")")
        return true
      }
      catch {
        print(error.localizedDescription)
        self.errorMessage = error.localizedDescription
        return false
      }
  }
}

Check out Getting started with Google Sign-In on Apple platforms - YouTube, in which I explain the configuration options in more detail.

huangapple
  • 本文由 发表于 2023年2月10日 02:49:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定