2015-02-08 66 views
1

GTMOAuth 2.0似乎是iOS上OAuth 2.0验证的极好工具。我试图通过在Xcode中实现GTMOAuth-2来检索Google用户的全名和电子邮件,但我遇到了一些麻烦。基于这个答案:Retrieve User email using GTM OAuth2 for iOS,它应该像拨打auth.userEmail一样简单。然而,问题是,在下面的代码段调用auth.userEmail总是返回nulliOS上的GTM OAuth 2.0 - 检索用户的电子邮件

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController 
    finishedWithAuth:(GTMOAuth2Authentication *)auth 
      error:(NSError *)error 
{ 
NSLog(@"finished"); 
NSLog(@"auth access token: %@", auth.accessToken); 

[self.navigationController popToViewController:self animated:NO]; 
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:@"Success Authorizing with Google" 
                message:[error localizedDescription] 
                delegate:nil 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 
    [alert show]; 
} 
NSLog(@"email: %@",auth.userEmail); 

}

代码成功运行并检索访问令牌,但auth.userEmail总是null。我是否需要使用GTMOAuth 2.0的Fetcher对象向Google电子邮件端点发送请求,或者使用auth.accessToken发送额外的HTTP GET请求来检索用户的电子邮件?

回答

0

我最近在弄Google OAuth2用于记录用户与gmail 按照tutsplus的教程和它给了我希望的results.I 会建议你遵循这个链接。这提供了 loginlogout以及登录用户的电子邮件地址的方法。 Google OAuth2 。并且要获得登录用户的电子邮件地址,请将其添加到范围 https://www.googleapis.com/auth/userinfo.email。和代码看起来 这样

[_googleOAuth authorizeUserWithClienID:@"YOUR CLIENT ID" 
          andClientSecret:@"SECRET" 
          andParentView:self.view 
           andScopes:[NSArray arrayWithObjects:@"https://www.googleapis.com/auth/userinfo.profile",@"https://www.googleapis.com/auth/userinfo.email", nil]]; 

而对于GTM的OAuth 2.0,添加此 范围https://www.googleapis.com/auth/userinfo.email。希望这可以帮助你 。