Skip to content

Instantly share code, notes, and snippets.

@SwiftfulThinking
Last active February 17, 2024 00:25
Show Gist options
  • Save SwiftfulThinking/3c2003a586a1ef50a7d7a5b7ea92de77 to your computer and use it in GitHub Desktop.
Save SwiftfulThinking/3c2003a586a1ef50a7d7a5b7ea92de77 to your computer and use it in GitHub Desktop.
Sign In With Google for iOS (async support)
//
//
//
//
//
//
// *****************************
// * THIS GIST HAS BEEN DEPRECATED. USE CODE HERE:
// https://github.com/SwiftfulThinking/SwiftfulFirebaseAuth/blob/main/Sources/SwiftfulFirebaseAuth/Helpers/SignInWithGoogle.swift
// *****************************
//
//
//
//
//
//
import SwiftUI
import GoogleSignIn
import GoogleSignInSwift
struct GoogleSignInResult {
let idToken: String
let accessToken: String
}
final class SignInWithGoogleHelper {
@MainActor
func signIn(viewController: UIViewController? = nil) async throws -> GoogleSignInResult {
guard let topViewController = viewController ?? topViewController() else {
throw URLError(.notConnectedToInternet)
}
let gidSignInResult = try await GIDSignIn.sharedInstance.signIn(withPresenting: topViewController)
guard let idToken = gidSignInResult.user.idToken?.tokenString else {
throw URLError(.badServerResponse)
}
let accessToken = gidSignInResult.user.accessToken.tokenString
return GoogleSignInResult(idToken: idToken, accessToken: accessToken)
}
@MainActor
func topViewController(controller: UIViewController? = nil) -> UIViewController? {
let controller = controller ?? UIApplication.shared.keyWindow?.rootViewController
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment