Forked from SwiftfulThinking/SignInWithGoogleHelper.swift
Created
March 25, 2023 12:03
-
-
Save EvolverSwiftUI/f10bf44c1fad294d271f7ec5cbd2944c to your computer and use it in GitHub Desktop.
Sign In With Google for iOS (async support)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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