我在 iPhone 应用程序中集成了 Google+ iOS SDK。
一旦用户输入了帐户详细信息,我想保持用户登录。
问题是,如果应用程序被终止并再次打开,用户将退出,我需要让用户登录。
有没有办法存储访问令牌之类的东西并使用它而不是显示登录屏幕?还是因为谷歌本身在应用程序终止时注销了用户?
3 回答
就我而言,使GPPSignIn
对象全局化解决了这个问题。
以下是如何做到这一点:
在Supporting Files
文件夹->appname-Prefix.pch
文件中,添加以下行:
#import <GooglePlus/GooglePlus.h>
GPPSignIn * signIn;
在这行下面:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
iOS 9,xcode 7.0.1 解决此问题的当前版本是
(void) signInSilently
使用GIDSignIn对象引用调用它。
由 google 提供:尝试在没有交互的情况下登录以前经过身份验证的用户。 参考链接
作为回应,它将返回
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error{}
如果用户过期或注销,则( GIDGoogleUser *)user将为空,并且在登录用户的情况下,详细信息将带有(NSError *)error,反之亦然。
希望它会帮助某人。
用于 Google+ 登录。这里有几个步骤如下
1.> 首先添加 Google+ SDK 并在点击“API 访问窗格”下创建 Google+ 客户端 ID
插入GoogleOpenSource.framework ,* GooglePlus.bundle *, GooglePlus.framework
ClientID
2.> 现在为这样的全局分配一个宏
#define kClientID @"//paas client id which your app provided by developer account portal";
3.> 在你的AppDelegate.h
文件中实现它
#import <GooglePlus/GooglePlus.h>
extern NSString *const FBSessionStateChangedNotification;
@interface AppDelegate : UIResponder <UIApplicationDelegate,GPPDeepLinkDelegate>
{
}
-(void)clearApplicationCaches;
4.>在你的AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[GPPSignIn sharedInstance].clientID = kClientID;
[GPPDeepLink setDelegate:self];
[GPPDeepLink readDeepLinkAfterInstall];
[self.window makeKeyAndVisible];
return YES;
}
- (void)didReceiveDeepLink:(GPPDeepLink *)deepLink
{
}
#pragma mark - Memory management methods
-(void)clearApplicationCaches
{
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[self clearApplicationCaches];
}
- (BOOL)application: (UIApplication *)application openURL: (NSURL *)url sourceApplication: (NSString *)sourceApplication annotation: (id)annotation
{
return [GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation];
}
提示:如果您想测试到这一点,您可以[signIn authenticate]
在方法结束时调用viewDidLoad
。该应用程序将在启动时将您重定向到登录对话框
5.> 现在转到您的视图控制器并在yourViewController.h
文件中
#import <GooglePlus/GooglePlus.h>
@class GPPSignInButton;
@interface yourViewController:UIViewController <GPPSignInDelegate>
{
}
@property(nonatomic, strong) IBOutlet GPPSignInButton *signInButton;
如有必要,合成GPPSignInButton
属性,尽管在较新版本的 Xcode 中不再需要此步骤。
@synthesize signInButton;
- (void)viewDidLoad
{
[super viewDidLoad];
[GPPSignInButton class];
GPPSignIn *signIn = [GPPSignIn sharedInstance];
signIn.clientID = kClientID;
signIn.delegate = self;
[signIn trySilentAuthentication]; /// this calls finishedWithAuth automatically
}
添加GPPSignInButton
到您的故事板、XIB 文件或以编程方式对其进行实例化。GPPSignInButton
继承自UIButton
,因此如果您使用的是故事板或 XIB 文件,您可以将圆形矩形按钮或视图拖到视图控制器上并将其自定义类设置为GPPSignInButton
.
将按钮连接到signInButton
视图控制器的属性。
#pragma mark -
#pragma mark - GooglePluseDelegate Implementation
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth error: (NSError *) error
{
NSLog(@"email %@ ",[NSString stringWithFormat:@"Email: %@",[GPPSignIn sharedInstance].authentication.userEmail]);
NSLog(@"Received error %@ and auth object %@",error, auth);
// 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];
GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:@"me"];
// *4. Use the "v1" version of the Google+ API.*
plusService.apiVersion = @"v1";
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPerson *person,
NSError *error) {
if (error) {
GTMLoggerError(@"Error: %@", error);
[MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
} else
{
NSLog(@"userId = %@",query.activityId);
NSLog(@"person = %@",[person.name.familyName stringByAppendingFormat:@" %@",person.name.givenName]);
NSLog(@"person = %@", person);
NSDictionary *tempDic = [NSDictionary dictionaryWithObjectsAndKeys:[GPPSignIn sharedInstance].authentication.userEmail,@"email",person.identifier,@"googleID",[person.name.givenName stringByAppendingFormat:@" %@",person.name.familyName],@"name",[person.name.givenName stringByAppendingFormat:@" %@",person.name.familyName],@"username",person.gender,@"gender", nil];
[NSThread detachNewThreadSelector:@selector(parsingLoginWithGoogleApi:) toTarget:self withObject:tempDic];
}
}];
}
// ---- its call a web service to login with google+ info
-(void) parsingLoginWithGoogleApi:(NSDictionary*) googleUserInfoDic
{
NSLog(@"google User Info Dic = %@", googleUserInfoDic );
NSString *name = @"";
NSString *username = @"";
NSString *emailId = @"";
NSString *gender = @"";
NSString *apiURLStr =@"";
if ([DEFAULTS objectForKey:@"isLogin"])
{
name =[DEFAULTS objectForKey:@"g_name"];
emailId =[DEFAULTS objectForKey:@"g_emailId"];
username =[DEFAULTS objectForKey:@"g_username"];
gender =[DEFAULTS objectForKey:@"g_gender"];
apiURLStr =[NSString stringWithFormat:@"%@google_login/%@/%@/%@/%@",SiteAPIURL,emailId,[name stringByURLEncode],[username stringByURLEncode],gender];
}
else
{
name =[googleUserInfoDic valueForKey:@"name"];
username =[googleUserInfoDic valueForKey:@"username"];
emailId = @"0";
if ([googleUserInfoDic valueForKey:@"email"])
emailId=[googleUserInfoDic valueForKey:@"email"];
gender = @"0";
if ([googleUserInfoDic valueForKey:@"gender"])
gender =[googleUserInfoDic valueForKey:@"gender"];
apiURLStr =[NSString stringWithFormat:@"%@google_login/%@/%@/%@/%@",SiteAPIURL,emailId,[name stringByURLEncode],[username stringByURLEncode],gender];
}
NSLog(@"login Google apiURLStr==>>>%@",apiURLStr);
NSString *outputStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiURLStr] encoding:NSUTF8StringEncoding error:nil];
NSLog(@"login Google response==>>>%@",outputStr);
if (outputStr == NULL)
{
NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"There was a small problem",@"title",@"The network doesn't seem to be responding, please try again.",@"message",@"OK",@"cancel",@"1",@"tag",self,@"delegate", nil];
[CommonFunctions performSelectorOnMainThread:@selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];
[MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
}
else
{
NSDictionary *jsonResponse = [outputStr JSONValue];
if (jsonResponse != nil)
{
NSString *replycode=[jsonResponse objectForKey:@"replyCode"];
if ([replycode isEqualToString:@"success"])
{
NSUserDefaults *userDefs = [NSUserDefaults standardUserDefaults];
[userDefs setObject:name forKey:@"g_name"];
[userDefs setObject:emailId forKey:@"g_emailId"];
[userDefs setObject:username forKey:@"g_username"];
[userDefs setObject:gender forKey:@"g_gender"];
[userDefs setObject:[jsonResponse objectForKey:@"sesId"] forKey:@"sessionId"];
sessionId = [jsonResponse objectForKey:@"sesId"];
[userDefs setObject:username forKey:@"username"];
[userDefs setObject:[jsonResponse objectForKey:@"userId"] forKey:@"userId"];
[userDefs setObject:@"YES" forKey:@"isLogin"];
[userDefs setObject:@"Google" forKey:@"LoginType"];
userId = [jsonResponse objectForKey:@"userId"];
[userDefs synchronize];
[MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
[self performSelectorOnMainThread:@selector(pushProfileVC:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:NO];
}
else
{
[MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:replycode,@"title",[jsonResponse objectForKey:@"replyMsg"],@"message",@"OK",@"cancel",@"1",@"tag",nil,@"delegate", nil];
[CommonFunctions performSelectorOnMainThread:@selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];
}
}
else
{
[MBProgressHUD hideHUDForView:[[UIApplication sharedApplication]keyWindow] animated:TRUE];
NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"There was a small problem",@"title",@"The network doesn't seem to be responding, please try again.",@"message",@"OK",@"cancel",@"1",@"tag",self,@"delegate", nil];
[CommonFunctions performSelectorOnMainThread:@selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];
}
}
}
我希望它会帮助你。谢谢