idoodler
idoodler

Reputation: 3545

Stay signed in to Google OAuth 2.0 service in iOS

I am writing an application that should displays the current AdSense data, my problem is every time I open the application I am prompted with the GTMAuth2ViewControllerTouch, so the familiar Google OAuth 2.0 login screen (I used this to do the login stuff). How can I sign in once and then the user is signed in forever? In the tutorial there is a kKeychainItemName, but it is just a string, how can I use this to automatically sign in the user? Take a look at the ViewDidLoad.

That is the code I use:

#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];

}

Upvotes: 4

Views: 1191

Answers (1)

Karthi
Karthi

Reputation: 575

In "awakeFromNib:" method, check for the authentication to know whether the the user has already signedIn. If the user is already signed in navigate to the next view or next screen which you want to take the user after signedin.

-(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];
}

Here you can check whether the user is authorized, by calling '-canAuthorize' method. It checks for authorization and return true flag if it is authorized.

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

Upvotes: 2

Related Questions