自定义Google登录按钮 - iOS

时间:2015-12-19 07:54:03

标签: ios iphone swift ios9 google-signin

我想自定义Google登录按钮,如下所示: - enter image description here
我试过下面的链接,但没有一个真的有用: - How to customize google sign in button? {
{3}}

有人可以指导我应该做什么吗?我无法使用Google+登录按钮,因为“https://developers.google.com/identity/sign-in/ios/”。

编辑: - 我尝试了以下链接提供的代码: -
Google+ Sign-In is deprecated

10 个答案:

答案 0 :(得分:91)

您可以添加自己的按钮,而不是使用Google登录按钮 做事情

Objective C Version

1)将自己的按钮添加到storyBoard

2)将动作拖动到viewController

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

3)处理委托方法

#pragma mark - Google SignIn代表

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

  }

//提供一个视图,提示用户使用Google登录

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

//关闭“使用Google登录”视图

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

}

//已完成登录

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

Swift 4版本

在Swift中确保添加了briding header,因为库是用Objective C编写的

1)将自己的按钮添加到storyBoard

2)将动作拖动到viewController

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

3)处理委托方法

// MARK:Google SignIn代表

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

//提供一个视图,提示用户使用Google登录

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

//关闭“使用Google登录”视图

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

//已完成登录

   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)")
        }
    }

编辑:以下是使用自定义按钮Google Doc reference

的参考/证据
  

5.如果要自定义按钮,请执行以下操作:在视图控制器的.h文件中,将登录按钮声明为属性。

@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
     

将按钮连接到刚刚声明的signInButton属性。   通过设置GIDSignInButton的属性来自定义按钮   宾语。接下来,您可以实现并处理注销按钮。

答案 1 :(得分:7)

Swift 3版

在Swift中,确保添加了briding header,因为库是用目标C编写的。

  1. 将自己的按钮添加到storyBoard
  2. 将动作拖动到viewController

    @IBAction func googlePlusButtonTouchUpInside(sender: AnyObject) {
          GIDSignIn.sharedInstance().signIn()
    } 
    
  3. 处理委托方法

    //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)")
            }
        }
    

答案 2 :(得分:7)

对于Swift 4 :(这是工作代码享受)

@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)")
    }
}

答案 3 :(得分:3)

@Rohit KP (https://stackoverflow.com/a/34368678/2905967)

的回答一切正常

但是在分配代表时很少添加。

请按照以下方式致电您的行动:

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

并添加这些代理GIDSignInDelegate,GIDSignInUIDelegate

答案 4 :(得分:1)

您可以添加自己的按钮,而不是使用Google登录按钮执行以下操作

1)在AppDelegate.m文件中添加此代码

2)将自己的按钮添加到storyBoard中,并将类名称作为GPPSignInButton并在该按钮上设置UIImageView。

3)将动作拖动到viewController

AppDelegate.m文件

- (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);
                        }
                    }];

        }
    }
}

答案 5 :(得分:1)

对于Swift 4.2

创建自定义Google按钮:

1-将按钮添加到情节提要

2-为您的按钮创建@IBaction

按照https://developers.google.com/identity/sign-in/ios/sign-in的3条说明进行操作 但请替换此步骤

“ 2。在视图控制器中,重写viewDidLoad方法以设置GIDSignIn对象的UI委托,并(可选)在可能的情况下以静默方式登录”

->将此代码插入按钮操作

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

现在您可以愉快地自定义按钮,希望此答案对您有所帮助。

答案 6 :(得分:1)

在GoogleSignIn SDK 5.0及更高版本中,GIDSignInUIDelegate已被撤销

添加以下行,以用于自定义Google登录按钮

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

答案 7 :(得分: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()
}

答案 8 :(得分:0)

尝试使用swift,它非常简单,就像一个冠军。

  1. 为您的Google登录按钮创建参考

    @IBOutlet weak var signInButton:GIDSignInButton!

  2. 在viewDidLoad中设置样式

    override func viewDidLoad() {
    super.viewDidLoad()
    //Do any additional setup after loading the view.
      signInButton.style = GIDSignInButtonStyle.iconOnly
    
  3. 3.将自定义按钮放在主故事板中的Google登录按钮上方,并为其创建操作参考。在其中以编程方式单击谷歌登录按钮。

        @IBAction func googleSignIn(_ sender: Any) {
        signInButton.sendActions(for: .touchUpInside)
        }
    

答案 9 :(得分:0)

Swift-5

@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)")
    }
}