目录
1.在Google Cloud后台配置客户端ID
2.iOS配置URL Types编辑
3.代码实操
1.在Google Cloud后台配置客户端ID
首先要在 Google Cloud 中创建一个项目。新创建的Project需要先配置同意屏幕。一共有4步骤需要配置。
1.OAuth 同意屏幕
User Type选择"外部"进行创建。填写必必要的信息,应用名称、用户支持电子邮件地址、开发者电子邮件地址 。
2.范围
该步骤选择默认即可
3.测试用户
必须要添加测试用户(只有填写的测试用户才能登录测试)
4.摘要
所有信息会在这里展示,可以进行修改。
创建OAuth客户端ID
保存下载的JSON文件,文件中有一个REVERSED_CLIENT_ID字段后续会用到。
2.iOS配置URL Types
在项目中AddPackage,填写GoogleSignIn
3.代码实操
此代码支持GoogleSignIn 6.X版本,不支持7.0.0版本
GoogleSignInHelper.h
#ifndef GoogleSignInHelper_h
#define GoogleSignInHelper_h// A view controller for the Google Sign-In button which initiates a standard
// OAuth 2.0 flow and provides an access token and a refresh token. A "Sign out"
// button is provided to allow users to sign out of this application.
@interface GoogleSignInHelper : NSObject@property(nonatomic, readonly) UIViewController* viewController;+ (GoogleSignInHelper *)getInstance;-(void)signIn;
-(void)signOut;@end#endif /* GoogleSignInHelper_h */
GoogleSignInHelper.m
#import "GoogleSignInHelper.h"#import <GoogleSignIn/GIDSignIn.h>
#import <GoogleSignIn/GIDGoogleUser.h>
#import <GoogleSignIn/GIDAuthentication.h>static NSString * const kClientID = @"com.googleusercontent.apps.462065624000-ducjftkt3lh1ini7f7q7j5ueq2vmo5o9";@implementation GoogleSignInHelper {// Configuration options for GIDSignIn.GIDConfiguration *_configuration;
}static GoogleSignInHelper *instance;+ (GoogleSignInHelper *)getInstance
{if (!instance) {instance = [[GoogleSignInHelper alloc] init];}return instance;
}- (id) init
{if (self = [super init]) {if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) {NSArray* array = [[UIApplication sharedApplication] windows];UIWindow* window = [array objectAtIndex:0];_viewController = (UIViewController*)[[[window subviews] objectAtIndex:0]nextResponder];} else {_viewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];}_configuration = [[GIDConfiguration alloc] initWithClientID:kClientID];}return self;
}-(void)signIn
{[GIDSignIn.sharedInstance signInWithConfiguration:_configurationpresentingViewController:_viewControllercallback:^(GIDGoogleUser * _Nullable user,NSError * _Nullable error) {if (error != nil) {if (error.code == kGIDSignInErrorCodeHasNoAuthInKeychain) {NSLog(@"The user has not signed in before or they have since signed out.");} else {NSLog(@"%@", error.localizedDescription);}} else {NSString *userId = user.userID; // For client-side use only!NSString *idToken = user.authentication.idToken; // Safe to send to the serverNSString *fullName = user.profile.name;NSString *givenName = user.profile.givenName;NSString *familyName = user.profile.familyName;NSString *email = user.profile.email;// todo:}}];
}-(void)signOut
{[GIDSignIn.sharedInstance signOut];
}@end
2023/5/19
GoogleSignIn库更新到7.0.0版本,此文章不再适用。