自定义谷歌登录按钮 - iOS

38

@Birendra 我已经编辑了我的问题。Google 没有提供太多的代码。你可以查看链接。我认为你没有完全阅读我的问题。 - Piyush Dubey
你好,如果你有Skype ID,请告诉我,这样我就可以发送一个代码给你。 - Birendra
你需要使用这段代码。 - Birendra
  • (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
在你的Appdelegate.m文件中 - Birendra
显示剩余3条评论
10个回答

101

你可以添加自己的按钮,而不是使用Google登录按钮 请按照以下步骤操作

Objective C版本

1)在storyboard中添加自己的按钮

2)将动作拖入视图控制器

- (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 中,确保您添加了桥接头文件,因为该库是用 Objective-C 编写的。

1)将您自己的按钮添加到故事板中。

2)将操作拖入视图控制器中。

@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!) {
}

// 呈现一个视图,提示用户使用谷歌账号登录

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文档参考

在这些示例中,视图控制器是UIViewController的子类。如果在您的项目中,实现GIDSignInUIDelegate的类不是UIViewController的子类,请实现GIDSignInUIDelegate协议的signInWillDispatch:error:、signIn:presentViewController:和signIn:dismissViewController:方法。还要记得设置UI代理 GIDSignIn.sharedInstance()?.uiDelegate = self


1
@Rohit KP。我在按钮方法中的[[GIDSignIn sharedInstance] signIn]处遇到了崩溃。 - Karthik Mandava
2
@TrongVu:不,没有拒绝应用程序的理由。我已经在应用商店上发布了带有自定义按钮的应用程序。我已编辑答案并添加了来自Google文档的参考。请查阅。感谢您的指出。 - Rohit Pradhan
如果您的类是UIViewController的子类,则不需要前三种方法。从Google ->“//仅在GIDSignInUIDelegate不是UIViewController的子类时实现这些方法。” - coolcool1994
1
首先设置委托和UIDelegate,然后调用GIDSignIn.sharedInstance().signIn()。享受! - Rohit Sisodia
1
@RohitSisodia 谢谢,我已经更新了答案。在从Objective C翻译成Swift时打错了。 - Rohit Pradhan
显示剩余7条评论

8

Swift 3 版本

在 Swift 中,确保添加了桥接头文件,因为该库是用 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)")
            }
        }
    

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

关于@Rohit KP (https://dev59.com/IlsX5IYBdhLWcg3wALXa#34368678)的答案都是正确的。

但是在分配代理时还需要添加一些内容。

请按照以下方式调用您的操作:

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

并添加这些代理 GIDSignInDelegate,GIDSignInUIDelegate


3
在GoogleSignIn SDK 5.0及以上版本中,GIDSignInUIDelegate已被废除。
为自定义的Google登录按钮添加以下行:
@IBAction func googleLoginPressed(sender: UIButton) {
    GIDSignIn.sharedInstance()?.presentingViewController = self
    GIDSignIn.sharedInstance()?.delegate = self
    GIDSignIn.sharedInstance()?.signIn()
}

谢谢!终于帮了我。非常微小的改变,但很容易被忽略。 - iHarshil

2

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

1

对于Swift 4.2

制作自定义Google按钮的方法:

1-将您的按钮添加到Storyboard中

2-为您的按钮创建@IBaction

3-按照https://developers.google.com/identity/sign-in/ios/sign-in上的说明进行操作,但替换这一步骤

"2.在视图控制器中,重写viewDidLoad方法以设置GIDSignIn对象的UI委托,并(可选)尽可能静默地登录"

用以下内容代替

-> 在按钮操作中插入此代码

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

现在你可以愉快地自定义按钮了,希望这个回答能帮到你。


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

        }
    }
}

GTLServicePlus服务停止支持(https://developers.google.com/+/mobile/ios/people)。我们必须使用Google登录。 - Trong Vu

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
虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题,将有助于提高您的帖子质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请[编辑]您的答案以添加解释并指出适用的限制和假设。 - Brian61354270

0

尝试使用Swift,它非常简单且像冠军一样有效。

  1. 为您的Google登录按钮创建引用

    @IBOutlet weak var signInButton: GIDSignInButton!

  2. 在viewDidLoad中设置其样式

    override func viewDidLoad() {
    super.viewDidLoad()
    //加载视图后进行任何其他设置。
      signInButton.style = GIDSignInButtonStyle.iconOnly
    

3. 在主story board中将您的自定义按钮放置在Google登录按钮上方,并为其创建一个操作引用。在其中以编程方式单击Google登录按钮。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接