38

I want to customize Google Sign-In button like below:-
enter image description here
I have tried below links, but none of them helped really much:- How to customize google sign in button?
https://developers.google.com/identity/sign-in/ios/

Could somebody please guide what I should do? I can't use Google+ Sign-In button because "Google+ Sign-In is deprecated".

Edited:- I tried the code provided on below link:-
https://developers.google.com/identity/sign-in/ios/sign-in#add_the_sign-in_button

Rohit Pradhan
  • 3,867
  • 1
  • 21
  • 29
Piyush Dubey
  • 2,416
  • 1
  • 24
  • 39
  • have you tried any code than paste in here – Birendra Dec 19 '15 at 07:58
  • @Birendra I have edited my question. There was not much code provided by Google. You can check the link. I think you haven't read my question completely. – Piyush Dubey Dec 19 '15 at 08:02
  • hi you have a skype id then give me so i can send a code – Birendra Dec 19 '15 at 08:12
  • you have use this code – Birendra Dec 19 '15 at 08:17
  • - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { GPPSignIn *SignIn = [GPPSignIn sharedInstance]; [GPPSignIn sharedInstance].clientID = @"532796865439-juut4g2toqdfc13mgqu5v9g5cliguvmg.apps.googleusercontent.com"; SignIn.scopes = @[kGTLAuthScopePlusLogin]; return YES; } – Birendra Dec 19 '15 at 08:17
  • -(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { if ([GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation]) { return YES; } return wasHandled; } – Birendra Dec 19 '15 at 08:18
  • In your Appdelegate.m file – Birendra Dec 19 '15 at 08:18
  • hi if not done than I update my answer so please check it and if any issue then tell me – Birendra Dec 19 '15 at 09:23

10 Answers10

101

You can add your own button instead of using Google Sign-In button Do follwing things

Objective C Version

1)Add your own button into storyBoard

2)drag action into viewController

- (IBAction)googlePlusButtonTouchUpInside:(id)sender {
     [GIDSignIn sharedInstance].delegate = self;
     [GIDSignIn sharedInstance].uiDelegate = self;
     [[GIDSignIn sharedInstance] signIn];
  }

3)handle delegate methods

#pragma mark - Google SignIn Delegate

- (void)signInWillDispatch:(GIDSignIn *)signIn error:(NSError *)error {

  }

// Present a view that prompts the user to sign in with Google

- (void)signIn:(GIDSignIn *)signIn presentViewController:(UIViewController *)viewController
{
    [self presentViewController:viewController animated:YES completion:nil];
}

// Dismiss the "Sign in with Google" view

- (void)signIn:(GIDSignIn *)signIn dismissViewController:(UIViewController *)viewController {
    [self dismissViewControllerAnimated:YES completion:nil];

}

//completed sign In

- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
//user signed in
//get user data in "user" (GIDGoogleUser object)
}

Swift 4 Version

In Swift make sure you have added briding header as the library is written in objective C

1)Add your own button into storyBoard

2)drag action into viewController

@IBAction func googlePlusButtonTouchUpInside(sender: AnyObject) {
      GIDSignIn.sharedInstance().delegate=self
      GIDSignIn.sharedInstance().uiDelegate=self
      GIDSignIn.sharedInstance().signIn()
} 

3)handle delegate methods

//MARK:Google SignIn Delegate

func signInWillDispatch(_ signIn: GIDSignIn!, error: Error!) {
}

// Present a view that prompts the user to sign in with Google

func signIn(_ signIn: GIDSignIn!,
    presentViewController viewController: UIViewController!) {
  self.present(viewController, animated: true, completion: nil)
}

// Dismiss the "Sign in with Google" view

func signIn(_ signIn: GIDSignIn!,
    dismissViewController viewController: UIViewController!) {
  self.dismiss(animated: true, completion: nil)
}

//completed sign In

   public func signIn(_ signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
      withError error: Error!) {
        if (error == nil) {
          // 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
          // ...
        } else {
          print("\(error.localized)")
        }
    }

Edit: Here is the reference/evidence for usage of custom button, Google Doc reference

In these examples, the view controller is a subclass of UIViewController. If, in your project, the class that implements GIDSignInUIDelegate is not a subclass of UIViewController, implement the signInWillDispatch:error:, signIn:presentViewController:, and signIn:dismissViewController: methods of the GIDSignInUIDelegate protocol. Also don't forget to set UI delegate GIDSignIn.sharedInstance()?.uiDelegate = self

Rohit Pradhan
  • 3,867
  • 1
  • 21
  • 29
  • Ok. Let me try this. Thanks. – Piyush Dubey Dec 19 '15 at 08:09
  • 1
    @Rohit KP. I am getting crash at [[GIDSignIn sharedInstance] signIn] in button method. – Karthik Mandava Aug 22 '16 at 07:35
  • Does apple will rejecte the app due to own button instead of using Google Sign-In button ? – Trong Vu Aug 27 '16 at 02:26
  • 2
    @TrongVu: No, There is no reason for rejecting App. I already have app live on App store with the custom button. I have edited the answer & added reference from google document. Please refer it. Thanks for pointing. – Rohit Pradhan Aug 28 '16 at 03:51
  • i am trying to use custom image , it is not working with custom image. above code is not working.if i use the above code , button clicked does nothing. – Logic Aug 29 '16 at 08:52
  • Calling signOut before calling signIn will bring up the prompt window again – Arash Zeinoddini Sep 11 '16 at 21:41
  • First three methods are not needed if your class is subclass of UIViewController. From Google -> "// Implement these methods only if the GIDSignInUIDelegate is not a subclass of // UIViewController." – coolcool1994 Jun 07 '17 at 14:17
  • 1
    First Set the delegate, and UIDelegate then call GIDSignIn.sharedInstance().signIn() Enjoy – Rohit Sisodia Dec 24 '17 at 07:36
  • 1
    @RohitSisodia thanks, I have updated the answer. It was mistyped while translating to swift from objective C. – Rohit Pradhan Dec 24 '17 at 09:05
  • Why not mention the actual delegate that must be added to the VC declaration? – Vahid Amiri Mar 23 '18 at 16:03
  • nice work @RohitKP for swift 4.0 we have updated your answer in swift 4.1 – Abhimanyu Daspan Aug 25 '18 at 07:45
  • `uiDelegate` is no more working. Please refer to the following link for updates: [link](https://developers.google.com/identity/sign-in/ios/quick-migration-guide#objective-c) – Sam Aug 26 '20 at 18:29
8

Swift 3 Version

In Swift make sure you have added briding header as the library is written in objective C.

  1. Add your own button into storyBoard
  2. drag action into viewController

    @IBAction func googlePlusButtonTouchUpInside(sender: AnyObject) {
          GIDSignIn.sharedInstance().signIn()
    } 
    
  3. handle delegate methods

    //MARK:Google SignIn Delegate
     func signInWillDispatch(signIn: GIDSignIn!, error: NSError!) {
      // myActivityIndicator.stopAnimating()
        }
    
    // Present a view that prompts the user to sign in with Google
       func sign(_ signIn: GIDSignIn!,
                  present viewController: UIViewController!) {
            self.present(viewController, animated: true, completion: nil)
        }
    
    // Dismiss the "Sign in with Google" view
     func sign(_ signIn: GIDSignIn!,
                  dismiss viewController: UIViewController!) {
            self.dismiss(animated: true, completion: nil)
        }
    
    //completed sign In    
    public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    
            if (error == nil) {
          // 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
              // ...
            } else {
                print("\(error.localizedDescription)")
            }
        }
    
ShrikantWalekar
  • 145
  • 1
  • 6
7

For Swift 4: (This is working code Enjoy)

@IBAction func logimByGoogle(_ sender: Any) {
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signIn()
}
//MARK:- Google Delegate
func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {

}

func sign(_ signIn: GIDSignIn!,
          present viewController: UIViewController!) {
    self.present(viewController, animated: true, completion: nil)
}

public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
                   withError error: Error!) {
    if (error == nil) {
        // 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
        // ...
    } else {
        print("\(error)")
    }
}
Rohit Sisodia
  • 895
  • 12
  • 13
3

All are fine with the answer of @Rohit KP (https://stackoverflow.com/a/34368678/2905967)

But Little adding when assigning the delegates.

Please call your action like this:

- (IBAction)btnGooglePlusPressed:(id)sender
{
    [GIDSignIn sharedInstance].delegate=self;
    [GIDSignIn sharedInstance].uiDelegate=self;
    [[GIDSignIn sharedInstance] signIn];
}

and add these delegates GIDSignInDelegate,GIDSignInUIDelegate

Community
  • 1
  • 1
Manab Kumar Mal
  • 20,788
  • 5
  • 31
  • 43
3

In GoogleSignIn SDK 5.0 and above GIDSignInUIDelegate has been revoked

Add this below line, for custom google login button

@IBAction func googleLoginPressed(sender: UIButton) {
    GIDSignIn.sharedInstance()?.presentingViewController = self
    GIDSignIn.sharedInstance()?.delegate = self
    GIDSignIn.sharedInstance()?.signIn()
}
2

Swift-5 Copy paste and Enjoy

@IBAction func btngoogle(_ sender: UIButton) {
    GIDSignIn.sharedInstance().signIn()
}


//MARK:Google SignIn Delegate
func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
    // myActivityIndicator.stopAnimating()
}
// Present a view that prompts the user to sign in with Google
func sign(_ signIn: GIDSignIn!,
          present viewController: UIViewController!) {
    self.present(viewController, animated: true, completion: nil)
}

// Dismiss the "Sign in with Google" view
func sign(_ signIn: GIDSignIn!,
          dismiss viewController: UIViewController!) {
    self.dismiss(animated: true, completion: nil)
}

//completed sign In
public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

    if (error == nil) {
        // 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
        // ...
    } else {
        print("\(error.localizedDescription)")
    }
}
Shakeel Ahmed
  • 5,361
  • 1
  • 43
  • 34
1

You can add your own button instead of using Google Sign-In button Do follwing things

1)Add this code in AppDelegate.m file

2)Add your own button into storyBoard and give class name as GPPSignInButton and set UIImageView on that button.

3)drag action into viewController

AppDelegate.m file

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    GPPSignIn *SignIn = [GPPSignIn sharedInstance];

    [GPPSignIn sharedInstance].clientID = @"532796865439-juut4g2toqdfc13mgqu5v9g5cliguvmg.apps.googleusercontent.com";

    SignIn.scopes = @[kGTLAuthScopePlusLogin];
    return YES;
} 

-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation]) {

        return YES;
    }

    return wasHandled;
}




ViewController.m file

@property (strong, nonatomic) IBOutlet GPPSignInButton *btn;

- (void)viewDidLoad {
    [super viewDidLoad];

   [GPPSignIn sharedInstance].delegate = self;
    [[GPPSignIn sharedInstance] trySilentAuthentication];

    AppDelegate *appDelegate = (AppDelegate *)
    [[UIApplication sharedApplication] delegate];
  }



-(void) finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
{
    GPPSignIn *signIn = [GPPSignIn sharedInstance];
    signIn.shouldFetchGoogleUserEmail = YES;
    signIn.delegate = self;

    if (error == nil) {
        if(auth.canAuthorize){
            GTLServicePlus *service = [[GTLServicePlus alloc] init];
            [service setRetryEnabled:YES];
            [service setAuthorizer:auth];

            GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:@"me"];


            // 1. Create a |GTLServicePlus| instance to send a request to Google+.
            GTLServicePlus* plusService = [[GTLServicePlus alloc] init] ;
            plusService.retryEnabled = YES;

            // 2. Set a valid |GTMOAuth2Authentication| object as the authorizer.
            [plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];

            // 3. Use the "v1" version of the Google+ API.*
            plusService.apiVersion = @"v1";
            [plusService executeQuery:query
                    completionHandler:^(GTLServiceTicket *ticket,
                                        GTLPlusPerson *person,
                                        NSError *error) {
                        if (error) {
                            //Handle Error
                        } else {
                            NSLog(@"\nEmail= %@", [GPPSignIn sharedInstance].authentication.userEmail);
                            NSLog(@"\nGoogleID=%@", person.identifier);
                            NSLog(@"\nUser Name=%@", [person.name.givenName stringByAppendingFormat:@" %@", person.name.familyName]);
                            NSLog(@"\nGender=%@", person.gender);
                        }
                    }];

        }
    }
}
Birendra
  • 623
  • 1
  • 5
  • 17
  • GTLServicePlus service is stopping support (https://developers.google.com/+/mobile/ios/people). We have to use the Google Sign In – Trong Vu Aug 05 '16 at 08:18
1

For Swift 4.2

to make a custom Google button :

1-add your button to storyboard

2-create @IBaction for your button

3-follow instructions on https://developers.google.com/identity/sign-in/ios/sign-in but replace this step

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

with

-> insert this code in the button action

    GIDSignIn.sharedInstance().uiDelegate=self
    GIDSignIn.sharedInstance().signIn()

now you can happily customize your button,hope this answer help you.

Eman Shedeed
  • 114
  • 2
  • 9
1

Swift 5.2:-

Add below lines in your view controller

func googleLoginButtonPressed(sender: UIButton) {
    GIDSignIn.sharedInstance()?.presentingViewController = self
    GIDSignIn.sharedInstance()?.delegate = self
    GIDSignIn.sharedInstance()?.signIn()
}
  • 1
    While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 09 '20 at 14:21
0

Try this for swift, its very simple and works like a champ.

  1. Create reference for your Google Sign In button

    @IBOutlet weak var signInButton: GIDSignInButton!

  2. set style for it in viewDidLoad

    override func viewDidLoad() {
    super.viewDidLoad()
    //Do any additional setup after loading the view.
      signInButton.style = GIDSignInButtonStyle.iconOnly
    

3.Place your custom button above the google sign in button in main story board and create an action reference for it. Inside it click the google sign in button programmatically.

    @IBAction func googleSignIn(_ sender: Any) {
    signInButton.sendActions(for: .touchUpInside)
    }
Jarin Rocks
  • 975
  • 10
  • 17