How to add Google Login button to your iOS app using Swift
- November 26, 2019
- John Codeos
Today, I’m going to show you how to add a Sign in with Google button into your iOS app, using Google’s official library through Cocoapods.
Lets get started!
First, you need to have a Google account.
Go to https://console.developers.google.com/ and login with your account.
Press Select a project at the top left corner and in the new window press NEW PROJECT.
On the next page, give a name to your project and press CREATE
On the left side menu, go to OAuth consent screen and fill in the required fields and press SAVE
You don’t need to submit for verification because you don’t use any sensitive scope.
After that, from the left side menu, choose Credentials, press Create credentials and choose OAuth client ID from the dropdown menu.
On the next page, choose iOS give the Name of your app, Bundle ID, and press Create
A new window will pop up with the OAuth Client ID that we are going to use later.
Creating the Google Login Button
First, add Google’s official library to your project using Cocoapods.
pod 'GoogleSignIn' to your Podfile.
Update your pods with
pod update and open your iOS project from the .xworkspace file.
Create an UIButton in your ViewController and make an Outlet and an Action connection to your swift file. In this example, we called it googleLoginBtn and googleLoginBtnAction.
Add the library at the top of your swift file,
Go to your project configuration, choose your app from TARGETS and go to Info Tab.
At the bottom press URL Types to expand and the + symbol to add a new URL scheme.
At the URL Schemes paste your Client ID you created earlier, but in reverse.
The Client ID you get from the website is in format:
and you need to change it to:
and paste it.
Now, go to your swift file with the Google Login Button and initialize the Google Sign In Authorization screen.
Put the Client ID as you copied it from the Google API Console website, not in reverse!
Extend your ViewController and add the GIDSignInDelegate.
The method sign(didSignInFor) is called after the user has interacted with the Authentication page, even when they have cancelled the request.
The sign(didDisconnectWith) is called from the
GIDSignIn.sharedInstance().disconnect() where can be triggered when a user wants to disconnect the Google account from your app.
Usually this can be called when you have the option ‘Delete my account’ on the user’s profile settings.
Finally, add the following code to sign(didSignInFor) method to return user’s info.
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!