oAuth2 gmail集成错误

时间:2014-02-14 10:59:03

标签: ios iphone ios6 oauth-2.0 gmail

我正在使用GTMOAuth2库登录过程进行g邮件身份验证上帝但重定向时间错误

 #define GoogleAuthURL   @"https://accounts.google.com/o/oauth2/auth"
    #define GoogleTokenURL  @"https://accounts.google.com/o/oauth2/token"

    NSURL * tokenURL = [NSURL URLWithString:GoogleTokenURL];

        NSString * redirectURI = @"";

        GTMOAuth2Authentication * auth;

        auth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"google"
                                                                 tokenURL:tokenURL
                                                              redirectURI:redirectURI
                                                                 clientID:GoogleClientID
                                                             clientSecret:GoogleClientSecret];

        auth.scope = @"https://www.googleapis.com/auth/userinfo.profile";

        GTMOAuth2ViewControllerTouch * viewcontroller = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
                                                                                                    authorizationURL:[NSURL URLWithString:GoogleAuthURL]
                                                                                                    keychainItemName:@"OAuth Sample: Google Contacts" delegate:self
                                                                                                    finishedSelector:@selector(viewController:finishedWithAuth:error:)];

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




 Error Domain=com.google.GTMOAuth2 Code=-1001 "The operation couldn’t be completed. (com.google.GTMOAuth2 error -1001.)"

请帮帮我

2 个答案:

答案 0 :(得分:1)

//import GTMOAuth2Authentication , GTMOAuth2ViewControllerTouch

#define GoogleClientID    @"paster your client id"
#define GoogleClientSecret @"paste your client secret"
#define GoogleAuthURL   @"https://accounts.google.com/o/oauth2/auth"
#define GoogleTokenURL  @"https://accounts.google.com/o/oauth2/token"

-(void) SignInGoogleButtonClicked
{

 NSURL * tokenURL = [NSURL URLWithString:GoogleTokenURL];

    NSString * redirectURI = @"urn:ietf:wg:oauth:2.0:oob";

    GTMOAuth2Authentication * auth;

    auth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"google"
                                                             tokenURL:tokenURL
                                                          redirectURI:redirectURI
                                                             clientID:GoogleClientID
                                                         clientSecret:GoogleClientSecret];

    auth.scope = @"https://www.googleapis.com/auth/plus.me";

    GTMOAuth2ViewControllerTouch * viewcontroller = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
                                                                                                authorizationURL:[NSURL URLWithString:GoogleAuthURL]
                                                                                                keychainItemName:@"GoogleKeychainName" delegate:self
                                                                                                finishedSelector:@selector(viewController:finishedWithAuth:error:)];

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

}



//this method is called when authentication finished

- (void)viewController:(GTMOAuth2ViewControllerTouch * )viewController finishedWithAuth:(GTMOAuth2Authentication * )auth error:(NSError * )error
{

    if (error != nil) {

        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error Authorizing with Google"
                                                         message:[error localizedDescription]
                                                        delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil];
        [alert show];
    }
    else
    {

         UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert !"
                                                         message:@"success"
                                                        delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil];
        [alert show];

    }
}

试试这个

答案 1 :(得分:0)

尝试以下代码....可能它会帮助我的朋友...首先在ViewDidLoad中写下面的代码。

- (void)viewDidLoad
{
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *clientID = [defaults stringForKey:kGoogleClientIDKey];
NSString *clientSecret = [defaults stringForKey:kGoogleClientSecretKey];

GTMOAuth2Authentication *auth = nil;

if (clientID && clientSecret) {
    auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                                 clientID:clientID
                                                             clientSecret:clientSecret];
}




// Save the authentication object, which holds the auth tokens and
// the scope string used to obtain the token.  For Google services,
// the auth object also holds the user's email address.
self.auth = auth;

// Update the client ID value text fields to match the radio button selection
[self loadClientIDValues];
}

 - (void)loadClientIDValues {
// Load the client ID and secret from the prefs into the text fields
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
mClientIDField.text = [defaults stringForKey:kGoogleClientIDKey];
mClientSecretField.text = [defaults stringForKey:kGoogleClientSecretKey];
}

然后在gmail的登录操作下写下代码......

-(IBAction)gmailLogin
{
[self saveClientIDValues];//this is the method for saving the credentials of gmail account of particular user.

if (![self isSignedIn]) {
    // Sign in
    [self signInToGoogle];

} else {
    // Sign out
    [self signOut];
}

}

- (void)saveClientIDValues {
// Save the client ID and secret from the text fields into the prefs
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *clientID = mClientIDField.text;
NSString *clientSecret = mClientSecretField.text;

[defaults setObject:clientID forKey:kGoogleClientIDKey];
[defaults setObject:clientSecret forKey:kGoogleClientSecretKey];
}

检查用户是否已登录!!!!

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

然后如果没有登录用户,那么要登录...

 - (void)signInToGoogle {
[self signOut];
NSString *keychainItemName = nil;
keychainItemName = kKeychainItemName;

// For Google APIs, the scope strings are available
// in the service constant header files.
NSString *scope = @"https://www.googleapis.com/auth/plus.me";

// Typically, applications will hardcode the client ID and client secret
// strings into the source code; they should not be user-editable or visible.
//
// But for this sample code, they are editable.
NSString *clientID = @"Your Id";
NSString *clientSecret = @"Your Secret";

if ([clientID length] == 0 || [clientSecret length] == 0) {
 //   NSString *msg = @"The sample code requires a valid client ID and client secret to sign in.";
    return;
}

// Note:
// GTMOAuth2ViewControllerTouch is not designed to be reused. Make a new
// one each time you are going to show it.

// Display the autentication view.
SEL finishedSel = @selector(viewController:finishedWithAuth:error:);

GTMOAuth2ViewControllerTouch *viewController;
viewController = [GTMOAuth2ViewControllerTouch controllerWithScope:scope
                                                          clientID:clientID
                                                      clientSecret:clientSecret
                                                  keychainItemName:keychainItemName
                                                          delegate:self
                                                  finishedSelector:finishedSel];

NSDictionary *params = [NSDictionary dictionaryWithObject:@"en"
                                                   forKey:@"hl"];
viewController.signIn.additionalAuthorizationParameters = params;

// By default, the controller will fetch the user's email, but not the rest of
// the user's profile.  The full profile can be requested from Google's server
// by setting this property before sign-in:
//
viewController.signIn.shouldFetchGoogleUserProfile = YES;
//
// The profile will be available after sign-in as
//
// NSDictionary *profile = viewController.signIn.userProfile;
NSDictionary *profile = viewController.signIn.userProfile;
NSLog(@"%@",profile);
// Optional: display some html briefly before the sign-in page loads
NSString *html = @"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>";
viewController.initialHTMLString = html;

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

// The view controller will be popped before signing in has completed, as
// there are some additional fetches done by the sign-in controller.
// The kGTMOAuth2UserSignedIn notification will be posted to indicate
// that the view has been popped and those additional fetches have begun.
// It may be useful to display a temporary UI when kGTMOAuth2UserSignedIn is
// posted, just until the finished selector is invoked.
 }

如果每件事都是正确的,那么你将得到以下方法的结果......

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
  finishedWithAuth:(GTMOAuth2Authentication *)auth
             error:(NSError *)error {
  if (error != nil) {
    // Authentication failed (perhaps the user denied access, or closed the
    // window before granting access)
    NSLog(@"Authentication error: %@", error);
    NSData *responseData = [[error userInfo] objectForKey:@"data"]; // kGTMHTTPFetcherStatusDataKey
    if ([responseData length] > 0) {
        // show the body of the server's authentication failure response
        NSString *str = [[[NSString alloc] initWithData:responseData
                                               encoding:NSUTF8StringEncoding] autorelease];
        NSLog(@"%@", str);
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Eye News" message:@"Gmail Authentication Fail. Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];

    self.auth = nil;
} 
else
{
  viewController.signIn.shouldFetchGoogleUserProfile = YES;
    NSDictionary *profile = viewController.signIn.userProfile;
    NSLog(@"%@",profile);
 }
}

让我知道它是否有效!!!!

快乐编码!!!!