在iOS设备上保持登录Google OAuth 2.0服务

4
我正在编写一个应用程序,它应该显示当前的AdSense数据,但每次打开应用程序时,都会提示我GTMAuth2ViewControllerTouch,这是熟悉的Google OAuth 2.0登录屏幕(我使用这个来完成登录)。我该如何登录一次,然后用户永久登录?在教程中有一个kKeychainItemName,但它只是一个字符串,我如何使用它来自动登录用户?看一下ViewDidLoad。 这是我使用的代码:
#import "ViewController.h"
#import "GTMOAuth2Authentication.h"
#import "GTMOAuth2ViewControllerTouch.h"
#import "GTMOAuth2SignIn.h"
#import "GTMHTTPFetcher.h"

static NSString *const kKeychainItemName = @"OAuth2 AdZen: AdSense";
NSString *kMyClientID = @"xxxxxxxxx.apps.xxxxxxxxxxxxx.com";     // pre-assigned by service
NSString *kMyClientSecret = @"xxxxxxxxxx--xxxxx"; // pre-assigned by service

NSString *scope = @"https://www.googleapis.com/auth/adsense.readonly"; // scope for Google+ API


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (/*USER ALREADY LOGGED IN*/) {
    //DO THE LOGIN STUFF AUTOMATICALLY WITH THE KEYCHAINITEM
}
else
{

[self signInToGoogle];

}


}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)signInToGoogle
{
   GTMOAuth2ViewControllerTouch *viewController;
    viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope
                                                                 clientID:kMyClientID
                                                             clientSecret:kMyClientSecret
                                                         keychainItemName:kKeychainItemName
                                                                 delegate:self
                                                         finishedSelector:@selector(viewController:finishedWithAuth:error:)];

    [self.navigationController pushViewController:viewController animated:YES];

}

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuth2Authentication *)auth
                 error:(NSError *)error {
    if (error != nil) {
        // Authentication failed
        UIAlertView *fail = [[UIAlertView alloc] initWithTitle:@"AdZen"
                                                            message:[NSString stringWithFormat:@"Error, Authentication failed!\n %@",error]
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:@"Try again", nil];
        fail.tag = 1;

        [fail show];
        NSLog(@"Authentication failed!");
    } else {
        // Authentication succeeded
        UIAlertView *success = [[UIAlertView alloc] initWithTitle:@"AdZen"
                                                       message:[NSString stringWithFormat:@"Authentication succeeded!"]
                                                      delegate:self
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil];
        success.tag = 2;

        [success show];
        NSLog(@"Autzentication succeeded!");

    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        if (alertView.tag == 1) {
            [self signInToGoogle];
        }
    }



}

- (void)authentication:(GTMOAuth2Authentication *)auth
               request:(NSMutableURLRequest *)request
     finishedWithError:(NSError *)error {
    if (error != nil) {
        NSLog(@"Authentication failed! 1");
    } else {
        // Authentication succeeded

        NSLog(@"Autzentication succeeded! 1");

    }

}



- (void)awakeFromNib {
    // Get the saved authentication, if any, from the keychain.
    GTMOAuth2Authentication *auth;
    auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                                 clientID:kMyClientID
                                                             clientSecret:kMyClientSecret];

    // Retain the authentication object, which holds the auth tokens
    //
    // We can determine later if the auth object contains an access token
    // by calling its -canAuthorize method
    //[self setAuthentication:auth];
    //NSLog(@"Already logged in!");
}

-(IBAction)signout
{

    [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemName];

    UIAlertView *signedout = [[UIAlertView alloc] initWithTitle:@"AdZen"
                                                      message:@"You just signed out, please sign in to see your AdSense info."
                                                     delegate:self
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];    
    [signedout show];

    [self signInToGoogle];

}

您可以查看此链接:https://groups.google.com/forum/#!forum/gtm-oauth2,其中有关于如何启用令牌保留的文档。 - faterpig
1个回答

2
在 "awakeFromNib:" 方法中,检查认证以确定用户是否已经登录。如果用户已经登录,请导航到您希望在登录后引导用户的下一个视图或屏幕。
-(void)awakeFromNib {
    GTMOAuth2Authentication *auth = nil;
    auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                             clientID:kMyClientID
                                                         clientSecret:kMyClientSecret];

   //Retain the authentication object, which holds the auth tokens

  [self setAuthentication:auth]; 
  //self.auth = auth;   


   if([self isSignedIn]) {

      NextViewController *nextViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"NextViewController"];
     [self.navigationController pushViewController:nextViewController animated:YES];
   }
}

- (void)setAuthentication:(GTMOAuthAuthentication *)auth {
    mAuth = nil;
    mAuth = [auth retain];
}

您可以通过调用“-canAuthorize”方法来检查用户是否已授权。它会检查授权并在授权后返回true标志。

(BOOL)isSignedIn
{
   BOOL isSignedIn = self.auth.canAuthorize;
   return isSignedIn;
 }

[self setAuthentication:auth]; --> 这个方法里会有什么? - NSPratik
@Pratik 在 [self setAuthentication:auth] 方法中,我们将保留包含授权令牌的认证对象。代码如下:
  • (void)setAuthentication:(GTMOAuthAuthentication *)auth { mAuth = nil; mAuth = [auth retain]; }
请参考已编辑的答案。
- Karthi

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