How to login with Google SignIn without using pod, in Swift 2.0

Inwizards-blog-img

Hi,
In this blog I will tell you how to login with Google SignIn in Swift which is very important for quick signup as users don’t have time to fill the forms.

Create a new project
Open Xcode , create a new “Single Page Application” and select Swift as the programming language.
Download GoogleSignIn SDK by clicking on this link
https://developers.google.com/identity/sign-in/ios/sdk/

Add the SDK in your Xcode project

Extract the SDK archive you downloaded and copy the following files to your Xcode project:

GoogleSignIn.framework

GoogleSignIn.bundle

Add GoogleSignIn.bundle to your Xcode project’s Copy Bundle Resources build phase.


Link dependent frameworks to your Xcode project

Link the following frameworks to your Xcode project:



AddressBook.framework

StoreKit.framework

SystemConfiguration.framework

AssetsLibrary.framework

CoreLocation.framework

CoreMotion.framework

MessageUI.framework

libcurses.tbd

libz.tbd

Add the ObjC linker flag to the app target’s build settings:

Other Linker Flags: $(OTHER_LDFLAGS) -ObjC

Get a configuration file

Click the button below to get a configuration file to add to your project.

The configuration file provides service-specific information for your app. To get it, you must select an existing project for your app or create a new one. You’ll also need to provide a bundle ID for your app.

Set your project’s reversed client ID and bundle ID

In the Project > Target > Info > URL Types panel, create a new item and paste yourREVERSED_CLIENT_ID into theURL Schemes field. You can find yourREVERSED_CLIENT_IDin the GoogleService-Info.plist file.

Also in the Project > Target > Info > URL Types panel, create a new item and type your bundle identifier in the URL Schemes field.

Add Bridging Header

As GoogleSignIn.framework is available in Objective C, we need to add bridging header to our Swift project. By using bridging header, we can use Objective C code in our Swift application.

To add bridging header to the project

Create new file by File >> New >> File from the menu to add temporary file.

Select Objective-C File.

Click Next.

Add File Name.

Click on Next.

Click on Create.

It will ask to configure Objective-C bridging header.

Click on Create Bridging Header button.

It will create Objective-C bridging header file.

Add following line of code to Bridging Header file

#import <GoogleSignIn/GoogleSignIn.h>

Also, you will need to set the client ID directly using the value found in the GoogleService-Info.plist file:

Now Goto AppDelegate.swift File add ClientID

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?



var kClientID:String = “YOUR-CLIENT-ID”

In your app delegate’s application:didFinishLaunchingWithOptions: method, configure the

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool {

GIDSignIn.sharedInstance().clientID = kClientID

return true

}

Implement the application:openURL:options: method of your app delegate. The method should call thehandleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process.

@available(iOS 9.0, *)

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {

return GIDSignIn.sharedInstance().handleURL(url,

sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as! String?,

annotation: options[UIApplicationOpenURLOptionsAnnotationKey])

}

For your app to run on iOS 8 and older, also implement the deprecatedapplication:openURL:sourceApplication:annotation: method.

func application(application: UIApplication,openURL url: NSURL, sourceApplication: String?, annotation:AnyObject) -> Bool {

return GIDSignIn.sharedInstance().handleURL(url,sourceApplication: sourceApplication,annotation: annotation)

}

Now Goto ViewController.swift file

implement the GIDSignInDelegate,GIDSignInUIDelegate protocol to handle the sign-in process by defining the following methods:

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {

}

func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {

}

Add the sign-in button

Next, you will add the Google Sign-In button so that the user can initiate the sign-in process. Make the following changes to the view controller that manages your app’s sign-in screen:

class ViewController: UIViewController,GIDSignInUIDelegate,GIDSignInDelegate {



@IBOutlet weak var signInButton: GIDSignInButton!

}

In the view controller, override the viewDidLoad method to set the UI delegate of theGIDSignInobject, and (optionally) to sign in silently when possible.

GIDSignIn.sharedInstance().uiDelegate = self

GIDSignIn.sharedInstance().delegate = self

Here is the complete Code in ViewController.swift file

import UIKit

@objc(ViewController)

class ViewController: UIViewController,GIDSignInUIDelegate,GIDSignInDelegate {

@IBOutlet weak var signInButton: GIDSignInButton!

@IBOutlet weak var signOutButton: UIButton!

@IBOutlet weak var disconnectButton: UIButton!

@IBOutlet weak var statusText: UILabel!

@IBOutlet weak var NameText: UILabel!

@IBOutlet weak var EmailText: UILabel!

override func viewDidLoad() {

super.viewDidLoad()

GIDSignIn.sharedInstance().uiDelegate = self

GIDSignIn.sharedInstance().delegate = self

NSNotificationCenter.defaultCenter().addObserver(self,selector:“receiveToggleAuthUINotification:”,name:“ToggleAuthUINotification”,object: nil)

statusText.text = “Initialized Swift app…”

toggleAuthUI()

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

@IBAction func didTapSignOut(sender: AnyObject) {

GIDSignIn.sharedInstance().signOut()

statusText.text = “Signed out.”

toggleAuthUI()

}

@IBAction func didTapDisconnect(sender: AnyObject) {

GIDSignIn.sharedInstance().disconnect()

statusText.text = “Disconnecting.”

}



func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {

if (error == nil) {

let userId = user.userID

let idToken = user.authentication.idToken

let name = user.profile.name

let email = user.profile.email

NameText.text = name

EmailText.text = email

print(idToken)

NSNotificationCenter.defaultCenter().postNotificationName(“ToggleAuthUINotification”,object: nil,userInfo: [“statusText”: “Signed in Successfully(userId)”])

} else {

print((error.localizedDescription)”)

NSNotificationCenter.defaultCenter().postNotificationName(“ToggleAuthUINotification”, object: nil, userInfo:nil)

}

}

func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {

NSNotificationCenter.defaultCenter().postNotificationName(“ToggleAuthUINotification”,object: nil,userInfo: [“statusText”: “User has disconnected.”])

}

// [START toggle_auth]

func toggleAuthUI() {

if (GIDSignIn.sharedInstance().hasAuthInKeychain()){

// Signed in

signInButton.hidden = true

signOutButton.hidden = false

disconnectButton.hidden = false

} else {

signInButton.hidden = false

signOutButton.hidden = true

disconnectButton.hidden = true

statusText.text = “Google Sign in iOS Demo”

} }

override func preferredStatusBarStyle() -> UIStatusBarStyle {

return UIStatusBarStyle.LightContent

}



deinit {

NSNotificationCenter.defaultCenter().removeObserver(self,

name: “ToggleAuthUINotification”,

object: nil)

}

@objc func receiveToggleAuthUINotification(notification: NSNotification) {

if (notification.name == “ToggleAuthUINotification”) {

self.toggleAuthUI()

if notification.userInfo != nil {

let userInfo:Dictionary<String,String!> =

notification.userInfo as! Dictionary<String,String!>

self.statusText.text = userInfo[“statusText”]

} }

} }

You can download Demo project.

How to login with Google SignIn without using pod, in Swift 2.0

Post navigation


0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x