使用SwiftUI的Google登录和Firebase

np8igboo  于 2023-02-13  发布在  Swift
关注(0)|答案(1)|浏览(194)

大家好,我尝试在一个SwiftUI项目中使用googlefirebase登录。现在检查旧的实现方法,以及从网上得到的一些建议,我对这部分代码有问题

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
    }
  }
}

使用此authentication常量时出现错误

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

错误为Value of type 'GIDGoogleUser' has no member 'autentication'
我知道谷歌放弃了一些属性来取代它们...目前我如何在SwiftUI中更新谷歌登录实现?

bvn4nwqk

bvn4nwqk1#

以下是在使用最新版本(7.0.0)的x1e0 f1 a使用Google Sign-In时验证Firebase用户的方法:

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
      }
  }
}

这段代码是我目前正在制作的一段视频的一部分,我会用更多的细节来更新这个答案,但是目前这可能会对你有所帮助。

相关问题