Swift Google Login Tutorial
In this tutorial we will be setting up a Google Login app using Swift. Unfortunately as Swift updates quite often the Google documentation is occasionally outdated. In this case the best recommendation I have is to manually type the code out, the auto complete will take care of the syntax update in most cases 🙂
First of all we need to setup the Google Cocoapods libaries, if you do not have Cocoapods or are unsure as to what it is, check out our post on it here.
Setting Up Facebook Cocoapods
First of all create a new Single View application xcode project. Once you have set it up navigate to the project in your terminal and initialize CocoaPods with pod init. After this we need to add the following CocoaPod libraries to our Podfile:
pod ‘GoogleSignIn’
Our whole Podfile will look something like the following, in my case the project name is ‘GSignIn’
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'GSign' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for GSign pod 'GoogleSignIn' target 'GSignTests' do inherit! :search_paths # Pods for testing end target 'GSignUITests' do inherit! :search_paths # Pods for testing end end
Google Sign In Developer Setup & Project Config
Before we start writing some code head on over the the Google Developer guide on iOS integration. Select ‘Create An OAuth Client ID’ and select or create a project. Once this is down download the credentials plist file, we will need to use this later in setting up our XCode Project.
Back in XCode select your Project on the left side, then select it under targets. After this go to the info tab and add a new item under URL types. In the URL Schemes add the REVERSED_CLIENT_ID from the Credentials .plist file you downloaded earlier.
Coding Google Sign in with Swift
Now that our project is setup, its time to code! Head on over to your AppDelegate.swift file, to start off with add the import as follows:
import GoogleSignIn
Then add the GIDSignInDelegate protocol to our class.
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate
In Application didFinishLaunchingWithOptions ass the following lines. Add your CLIENT_ID instead from your credentials.plist file.
GIDSignIn.sharedInstance().clientID = "922249379731-1fq2gv5jfvhmp0gtdfmg7n50o2ou5jcs.apps.googleusercontent.com" GIDSignIn.sharedInstance().delegate = self
Next add the following function that are required by the Sign in delegate
// Required for sign in func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return GIDSignIn.sharedInstance().handle(url as URL?, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation]) } // Once a user Signs in with Google this function will be called. // If there is an error then print it // If the sign in was sucessfull get the users account details func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { print("\(error.localizedDescription)") } else { // 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(fullName) } } // This function is called when the user disconnects from the app func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // Perform any operations when the user disconnects from app here. print("User has disconnected") }
Now we have the AppDelegate setup, we can add the Sign In button to our view controller.
Add the following import to the ViewController
import GoogleSignIn
Then add the Google Sign In UI delegate
class ViewController: UIViewController, GIDSignInUIDelegate {
Now in your viewDidLoad add the following lines of code which will:
- Set the Sign In Button delegate to self (Required for the button to sign in)
- Will Sign In automatically silently in the background if the user is already Signed In
- Add a Google Sign In Button to the center of the screen
GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().signInSilently() let gSignIn = GIDSignInButton(frame: CGRect(x: 0, y: 0, width: 230, height: 48)) gSignIn.center = view.center view.addSubview(gSignIn)
Now run the app and you will be able to Sign In with your google account! You will notice once you Sign In the button does not change to a Sign Out Button like the Facebook Login SDK.
Adding Sign Out functionality
Adding Sign Out functionality to the Google Sign in is simple, just add the following:
@objc func signOut(_ sender: UIButton) { print("Signing Out") GIDSignIn.sharedInstance().signOut() }
Now to call the signOut function simply add the following code in viewDidLoad to create a sign out button!
// Add sign out button let signOut = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 30)) signOut.backgroundColor = UIColor.red signOut.setTitle("Sign Out", for: .normal) signOut.center = view.center signOut.center.y = view.center.y + 100 signOut.addTarget(self, action: #selector(self.signOut(_:)), for: .touchUpInside) self.view.addSubview(signOut)