简体   繁体   English

自定义 Google 登录按钮 - iOS

[英]Custom Google Sign-In button - iOS

I want to customize Google Sign-In button like below:-我想自定义 Google 登录按钮,如下所示:-
在此处输入图像描述
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/ 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 ".我无法使用 Google+ 登录按钮,因为“ Google+ 登录已弃用”。

Edited:- I tried the code provided on below link:-编辑:- 我尝试了以下链接提供的代码:-
https://developers.google.com/identity/sign-in/ios/sign-in#add_the_sign-in_button https://developers.google.com/identity/sign-in/ios/sign-in#add_the_sign-in_button

You can add your own button instead of using Google Sign-In button Do follwing things您可以添加自己的按钮而不是使用 Google 登录按钮 执行以下操作

Objective C Version目标 C 版本

1)Add your own button into storyBoard 1)将您自己的按钮添加到故事板中

2)drag action into viewController 2)将动作拖入viewController

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

3)handle delegate methods 3)处理委托方法

#pragma mark - Google SignIn Delegate #pragma mark - Google 登录委托

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

  }

// Present a view that prompts the user to sign in with Google // 呈现一个提示用户使用 Google 登录的视图

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

// Dismiss the "Sign in with Google" view // 关闭“使用 Google 登录”视图

- (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斯威夫特 4 版本

In Swift make sure you have added briding header as the library is written in objective C在 Swift 中,确保你已经添加了 briding header,因为库是用 objective C 编写的

1)Add your own button into storyBoard 1)将您自己的按钮添加到故事板中

2)drag action into viewController 2)将动作拖入viewController

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

3)handle delegate methods 3)处理委托方法

//MARK:Google SignIn Delegate //MARK:Google 登录代理

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

// Present a view that prompts the user to sign in with Google // 呈现一个提示用户使用 Google 登录的视图

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

// Dismiss the "Sign in with Google" view // 关闭“使用 Google 登录”视图

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.在这些示例中,视图控制器是 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.如果在您的项目中,实现 GIDSignInUIDelegate 的类不是 UIViewController 的子类,请实现 GIDSignInUIDelegate 协议的 signInWillDispatch:error:、signIn:presentViewController: 和 signIn:dismissViewController: 方法。 Also don't forget to set UI delegate GIDSignIn.sharedInstance()?.uiDelegate = self也不要忘记设置 UI 委托 GIDSignIn.sharedInstance()?.uiDelegate = self

Swift 3 Version斯威夫特 3 版本

In Swift make sure you have added briding header as the library is written in objective C.在 Swift 中,确保你已经添加了 briding header,因为库是用目标 C 编写的。

  1. Add your own button into storyBoard将您自己的按钮添加到故事板中
  2. drag action into viewController将动作拖入 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)") } }

For Swift 4: (This is working code Enjoy)对于 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)")
    }
}

All are fine with the answer of @Rohit KP (https://stackoverflow.com/a/34368678/2905967) @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并添加这些代表GIDSignInDelegate,GIDSignInUIDelegate

In GoogleSignIn SDK 5.0 and above GIDSignInUIDelegate has been revoked在 GoogleSignIn SDK 5.0 及更高版本中,GIDSignInUIDelegate 已被撤销

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

Swift-5 Copy paste and Enjoy 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)")
    }
}

You can add your own button instead of using Google Sign-In button Do follwing things您可以添加自己的按钮而不是使用 Google 登录按钮 执行以下操作

1)Add this code in AppDelegate.m file 1)在AppDelegate.m文件中添加这段代码

2)Add your own button into storyBoard and give class name as GPPSignInButton and set UIImageView on that button. 2)将您自己的按钮添加到故事板中,并将类名称命名为 GPPSignInButton 并在该按钮上设置 UIImageView。

3)drag action into viewController 3)将动作拖入viewController

AppDelegate.m file 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);
                        }
                    }];

        }
    }
}

For Swift 4.2对于斯威夫特 4.2

to make a custom Google button:制作自定义 Google 按钮:

1-add your button to storyboard 1-将您的按钮添加到故事板

2-create @IBaction for your button 2-为您的按钮创建@IBaction

3-follow instructions on https://developers.google.com/identity/sign-in/ios/sign-in but replace this step 3-按照https://developers.google.com/identity/sign-in/ios/sign-in上的说明进行操作,但替换此步骤

"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" “2.在视图控制器中,重写 viewDidLoad 方法以设置 GIDSignIn 对象的 UI 委托,并(可选)尽可能静默登录”

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.现在您可以愉快地自定义您的按钮了,希望这个答案对您有所帮助。

Swift 5.2:-斯威夫特 5.2:-

Add below lines in your view controller

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

Try this for swift, its very simple and works like a champ.快速尝试这个,它非常简单并且像冠军一样工作。

  1. Create reference for your Google Sign In button为您的 Google 登录按钮创建参考

    @IBOutlet weak var signInButton: GIDSignInButton! @IBOutlet 弱变量 signInButton:GIDSignInButton!

  2. set style for it in viewDidLoad在 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. 3.将您的自定义按钮放在主故事板中谷歌登录按钮的上方,并为其创建一个操作参考。 Inside it click the google sign in button programmatically.在其中以编程方式单击谷歌登录按钮。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM