ios - Add google Sign-In with SwiftUI - Stack Overflow

PHOTO EMBED

Sat Sep 12 2020 12:59:37 GMT+0000 (Coordinated Universal Time)

Saved by @vivek #swift

//
//  GoogleSignInButtonView.swift
//
//  Created by Ivan Schaab on 11/09/2019.
//  Copyright © 2019 Ivan Schaab. All rights reserved.
//
import GoogleSignIn
import SwiftUI

struct GoogleSignInButtonView: View {

    @EnvironmentObject var lvm: LoginViewModel

    var body: some View {
        HStack {
            Spacer()
            GoogleButtonViewControllerRepresentable { (token, user) in
                // Google Login Success
                // Now do Backend Validations
                self.lvm.loginOauth(token: token, user: user)
            }
            Spacer()
        }.frame(alignment: .center)
    }
}

class GoogleButtonUIKitViewController: UIViewController {

    var signInButton = GIDSignInButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        GIDSignIn.sharedInstance().clientID = Constants.GOOGLE_CLIENT_ID
        self.view.addSubview(signInButton)

        GIDSignIn.sharedInstance()?.presentingViewController = self

        // Automatically sign in the user.
        GIDSignIn.sharedInstance()?.restorePreviousSignIn()
    }
}

struct GoogleButtonViewControllerRepresentable: UIViewControllerRepresentable
{
    let vc = GoogleButtonUIKitViewController()
    var googleResponse: (String, User) -> Void

    func makeUIViewController(context: Context) -> GoogleButtonUIKitViewController {
        return vc
    }
    func updateUIViewController(_ uiViewController: GoogleButtonUIKitViewController, context: Context) {}
    func makeCoordinator() -> Coordinator {
        Coordinator(vc: vc, googleResponse: googleResponse)
    }

    static func dismantleUIViewController(_ uiViewController: GoogleButtonUIKitViewController, coordinator: GoogleButtonViewControllerRepresentable.Coordinator) {
        print("DISMANTLE")
    }

    class Coordinator: NSObject, GIDSignInDelegate  {
        var foo: (String, User) -> Void
        init(vc: GoogleButtonUIKitViewController, googleResponse: @escaping (String, User) -> Void) {
            self.foo = googleResponse
            super.init()
            GIDSignIn.sharedInstance()?.delegate = self
        }

        func sign(_ signIn: GIDSignIn!, didSignInFor googleUser: GIDGoogleUser!, withError error: Error!) {
            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.localizedDescription)")
                }
                return
            }
//            let userId = googleUser.userID                  // For client-side use only!
            let idToken = googleUser.authentication.idToken // Safe to send to the server
            let email = googleUser.profile.email

            if googleUser.profile.hasImage{
                let imageUrl = googleUser.profile.imageURL(withDimension: 120)
                print(" image url: ", imageUrl?.absoluteString ?? "NO URL")
            }

            let user : User = User(id: 1, name: googleUser.profile.givenName, surname: googleUser.profile.familyName, imgName: ""  , email: googleUser.profile.email)

            print("email: ",email ?? "NO EMAIL")

            foo(idToken! , user)
        }
    }
}



#if DEBUG
struct SomeRepView_Previews: PreviewProvider {
    static var previews: some View {
        GoogleSignInButtonView().environmentObject(LoginViewModel())
    }
}
#endif
content_copyCOPY

https://stackoverflow.com/questions/57924768/add-google-sign-in-with-swiftui