https://developers.google.com/identity/sign-in/ios/start-integrating
Step 1: Set up your CocoaPods dependencies
pod init
pod 'GoogleSignIn'
pod install
This creates an .xcworkspace
file for your application. Use this file for all future development on your application.
Step 2: Get an OAuth client ID
Step 3: configure XCode
Add a URL scheme to your project
Step 4: Code
import SwiftUI
import GoogleSignIn
@main
struct ddApp: App {
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(HomeGlobal())
.onOpenURL(perform: { url in
GIDSignIn.sharedInstance().handle(url)
})
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate, GIDSignInDelegate {
// Google sign on
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Initialize sign-in
GIDSignIn.sharedInstance().clientID = "568858996537-1a3efc6qm9j2msv44hnd0ttmugejvtrs.apps.googleusercontent.com"
GIDSignIn.sharedInstance().delegate = self
return true
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: 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 signed out.")
} else {
print("\(error.localizedDescription)")
}
return
}
// Perform any operations on signed in user here.
let userId = user.userID // For client-side use only!
let idToken = user.authentication.idToken // Safe to send to the server
let fullName = user.profile.name
let givenName = user.profile.givenName
let familyName = user.profile.familyName
let email = user.profile.email
print("userId: ", userId)
print("idToken: ", idToken)
print("fullName: ", fullName)
print("givenName: ", familyName)
print("familyName: ", familyName)
print("email: ", email)
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
}
}
GoogleSignView.swift
import Foundation
import SwiftUI
import GoogleSignIn
struct GoogleSignView: UIViewRepresentable {
func makeUIView(context: Context) -> some UIView {
let btn = GIDSignInButton()
GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.first?.rootViewController
GIDSignIn.sharedInstance()?.shouldFetchBasicProfile = true
GIDSignIn.sharedInstance()?.restorePreviousSignIn()
return btn
}
func updateUIView(_ uiView: UIViewType, context: Context) {
}
}