在iPhone中使用Google API与OAuth 2.0进行gmail登录

我找到了Google提供的服务,可以访问各种Google服务的Google APIs 。 我可以在iPhone中设置一个项目,并为iOS应用程序(通过OAuth2.0 )和本地应用程序创建API访问权限。 我想为我的iPhone应用程序使用本机API。 它的API给我的电子邮件,全名,名字,姓氏,google_id,性别,dob,profile_image。 如何在我的iPhone应用程序中使用这些应用程序,任何示例应用程序,可用的摘录?

请帮帮我。

这是我的代码:

-(void) loadGmail_Login
{
    NSString *keychainItemName = nil;
    if ([self shouldSaveInKeychain]) {
        keychainItemName = kKeychainItemName;
    }

    // For GTM applications, the scope is available as
    NSString *scope = @"http://www.google.com/m8/feeds/";

    // ### Important ###
    // GTMOAuthViewControllerTouch is not designed to be reused. Make a new
    // one each time you are going to show it.

    // Display the autentication view.
    GTMOAuthAuthentication *auth;
    auth = [GTMOAuthViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName];

    GTMOAuthViewControllerTouch *viewController = [[[GTMOAuthViewControllerTouch alloc]
                                                    initWithScope:scope
                                                    language:nil
                                                    appServiceName:keychainItemName
                                                    delegate:self
                                                    finishedSelector:@selector(viewController:finishedWithAuth:error:)] autorelease];

    // You can set the title of the navigationItem of the controller here, if you want.
    // 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 setInitialHTMLString:html];

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

}

- (void)viewController:(GTMOAuthViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuthAuthentication *)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);
        }

        [self setAuthentication:nil];
    }
    else
    {
        // save the authentication object
        [self setAuthentication:auth];

        // Just to prove we're signed in, we'll attempt an authenticated fetch for the
        // signed-in user
        [self doAnAuthenticatedAPIFetch];
    }

}

- (void)doAnAuthenticatedAPIFetch
{
    NSString *urlStr;

    // Google Contacts feed
    //
    //    https://www.googleapis.com/oauth2/v2/userinfo
    urlStr = @"http://www.google.com/m8/feeds/contacts/default/thin";

    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [mAuth authorizeRequest:request];

    NSError *error = nil;
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    if (data) {
        // API fetch succeeded
        NSString *str = [[[NSString alloc] initWithData:data
                                               encoding:NSUTF8StringEncoding] autorelease];
        NSLog(@"API response: %@", str);

        GGCXml_Adaptor *localAlphabetXMLParser = [[GGCXml_Adaptor alloc] init];
        [localAlphabetXMLParser processBooksXML:data];
        [localAlphabetXMLParser release];
        //        [self updateUI];



    } else {
        // fetch failed
        NSLog(@"API fetch error: %@", error);
    }
}

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

首先,您需要从Google API获取令牌,对于第一步,您将不得不按照本教程进行操作,并且在此链接的末尾有iOS的完整源代码,用于从Google API获取令牌

http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/

然后在下一步中,您必须将该令牌发送给Google API以请求用户数据,我只需要第一步就可以分享我的搜索结果


试试这个教程和源代码链接

..这对我来说很好。

1.教程参考: http //technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/

2. Api参考: https : //code.google.com/apis/console/

3.源代码: https //github.com/emysa341/Login-with-gmail-google-g--using-oath-2.0-protocol/archive/master.zip


我认为这会帮助其他人按照以下步骤将gmail与您的应用程序集成。

1.为您的项目添加以下课程。

GTMHTTPFetcher.h,GTMHTTPFetcher.m,GTMOAuth2Authentication.h,GTMOAuth2Authentication.m,GTMOAuth2SignIn.h,GTMOAuth2SignIn.m,GTMOAuth2ViewControllerTouch.h,GTMOAuth2ViewControllerTouch.m,GTMOAuth2ViewTouch.xib,SBJSON.h,SBJSON.m

你会在这里得到这些类:https://github.com/jonmountjoy/Force.com-iOS-oAuth-2.0-Example

注意 :如果你在ARC环境下工作,那么你必须禁用ARC以下文件:
GTMHTTPFetcher.m,GTMOAuth2Authentication.m,GTMOAuth2SignIn.m,GTMOAuth2ViewControllerTouch.m

要在Xcode 4中禁用源文件的ARC,请在Xcode中选择项目和目标。 在目标“构建阶段”选项卡下,展开编译源构建阶段,选择库源文件,然后按Enter打开编辑字段,然后键入-fno-objc-arc作为这些文件的编译器标志。

2.添加以下框架

security.framework , systemConfiguration.framework

3.注册您的应用程序到谷歌API API控制台...。 这里: https : //code.google.com/apis/console

然后转到ApiAccess部分,为iOS应用创建客户端ID。 那么你会得到clientID,ClientSecret和RedirectUrl

** 4。 现在是编码的时候了。 **
在您的控制器中创建一个登录按钮并为其设置操作。 这里当用户点击按钮SignInGoogleButtonClicked方法被调用。

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

    }
}
链接地址: http://www.djcxy.com/p/11677.html

上一篇: Using the Google APIs with OAuth 2.0 for gmail login in iPhone

下一篇: Setting session attributes for JUnits on Spring 3.2