Google Sign-In: SwiftUI
The Google Sign-In SDK provides an easy way to authenticate users google accounts. Most apps need to know the identity of a user. Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.
Add Google Sign In Package
After creating a new XCode project, Install the Google Sign-In dependencies in your project using SPM: File > Add Packages > Paste in the following URL
https://github.com/google/GoogleSignIn-iOS
Create Client Application ID
- Log Into Google Cloud Platform
- Navigate to APIs and Services > Credentials
3. Click on “Create Credentials” and select “OAuth client ID”
4. Complete the form and note the “Client ID” and “iOS URL scheme”
5. In your XCode project, under the Info URL Types insert the URL Scheme
To Sign Into Google, the library provides us with the following command:
GIDSignIn.sharedInstance.signIn(
with: signInConfig,
presenting: presentingViewController,
callback: { user, error in
//Completion Code
}
)
We need the “signInConfig” and the “presentingViewController”. We get as follows:
let signInConfig = GIDConfiguration.init(clientID: "CLIENT_ID")
and we need to get the set of scenes from UIApplication.shared. There is only one scene. Pull that scene out and downcast to UIWindowScene. Now you can access windowScene.windows. Take the first one and its rootViewController
guard let presentingViewController = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first?.rootViewController else {return}
Create User Auth Model for Application Environment
Let’s create an Environment Object to hold the state and functionality of all things auth:
The “checkStatus” function checks the status of the current Google user. If the user is signed in, the user details on the login view are updated and displayed accordingly. On initialization (init) and app start, the user's previous sign-in state is evaluated and the variables are adjusted accordingly.
At the application entry point, we’ll put this model into the application environment. All views in this hierarchy will have access to this model.
This will suit us well if we would like to access user information on a number of different screens.
Let’s now create a login screen to illustrate how we can use the user auth model.