Hi!
Today I am going to show to how to integrate Google Sign In to your app.

First of all create a project and install the following pod.

pod 'Google/SignIn'

Then go to this link:  Start Integrating Google Sign-In into your app.
Then click GET A CONFIGURATION FILE. Sign -in to your google account and it will redirect you to this page.

Click Enable Google Sign-In.

Next click Close then Generate configuration files. Then Download GoogleService-Info.plist.

Drag & drop that downloaded Info.plist to your project. Then click on your project -> Targets -> Info. Under your URL Types click +. Then select GoogleService-Info.plist and copy your REVERSED_CLIENT_ID and paste it in your URL Schemes.

Add a UIView, and two Buttons on your Storyboard. and set UIView class as GIDSignInButton and create @IBOutles for all buttons and @IBAction for custom sign-in and logout button.

Now in your AppDelegate do the following.

   
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        GIDSignIn.sharedInstance().clientID = kClient
        var configureError:NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")
       
        return true
    }
    func application(application: UIApplication,
                     openURL url: NSURL, options: [String: AnyObject]) -> Bool {
        return GIDSignIn.sharedInstance().handleURL(url,
                                                    sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
                                                    annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
    }

Where kClient is CLIENT_ID from GoogleService-Info.plist.

Now in your UIViewController.Swift, Implement delegate GIDSignInDelegate and GIDSignInUIDelegate, and in your viewDidLoad().

 override func viewDidLoad() {
        super.viewDidLoad()
        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().delegate = self
    }

In didSignInForUser, you’ll get the logged In user object. Then do the following

 func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
                withError error: NSError!) {
        if (error == nil) {
           
            let userId = user.userID
            let idToken = user.authentication.idToken
            let fullName = user.profile.name
            let profilePicture = String(GIDSignIn.sharedInstance().currentUser.profile.imageURLWithDimension(400))
            let email = user.profile.email
            logout.hidden = false
            customButton.hidden = true
            defaultButton.hidden = true
            print("Auth:\(idToken)\nUserId:\(userId)\nFullname:\(fullName)\nEmail:\(email)\nProfile Picture:\(profilePicture)")
            alert("Logged In", message: "Fullname:\(fullName)\nEmail:\(email)\nProfile Picture:\(profilePicture)")
        } else {
            print("\(error.localizedDescription)")
        }
    }

In your Custom Sign In button action. Just do this.

 GIDSignIn.sharedInstance().signIn()

In your Logout button.

 if GIDSignIn.sharedInstance().hasAuthInKeychain() == true {
        GIDSignIn.sharedInstance().signOut()
            logout.hidden = true
            customButton.hidden = false
            defaultButton.hidden = false
            alert("Logged Out", message: "")
        
        }

And at last for alert.

 func alert(title: String, message: String){
    let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    let okAction = UIAlertAction(title: "OK",style: .Default, handler: nil)
        alert.addAction(okAction)
        
        self.presentViewController(alert, animated: true, completion: nil)
    
    }

Build and Run your app and sign in with your Google account.

Source code on Github.
If you have any question, please leave a comment.

Happy Coding! 🙂

Share:

administrator

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he's probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

Leave a Reply

Your email address will not be published. Required fields are marked *