继续登录iOS中的Google OAuth 2.0服务

时间:2013-07-23 10:52:38

标签: ios objective-c google-api oauth-2.0 adsense

我正在编写一个应该显示当前AdSense数据的应用程序,我的问题是每次打开应用程序时我都会通过GTMAuth2ViewControllerTouch提示,所以熟悉的Google OAuth 2.0登录界面(我使用this做了登录的东西)。如何登录,然后用户永远登录?在教程中有一个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];

}

1 个答案:

答案 0 :(得分: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 flag(如果已获得授权)。

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