使用Google api与OAuth 2.0在iPhone上登录gmail



我找到了一个来自谷歌的服务,它提供了对各种谷歌服务的Google APIs的访问。我可以在iPhone上建立一个项目,并为iOS应用程序(通过OAuth2.0)和本地应用程序创建API访问。我想在iPhone应用中使用原生API,它给我email,全名,姓,名,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。GTMOAuth2Authentication.h、GTMOAuth2Authentication.m、GTMOAuth2SignIn.h、GTMOAuth2SignIn.m、GTMOAuth2ViewControllerTouch.h、gtmoauth2viewcontroller .xib、SBJSON.h、SBJSON.m

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

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

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

2。添加以下框架

security.framework , systemConfiguration.framework

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

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

* * 4。现在是时候编码. . . .**
在控制器中创建一个signIn按钮,并为其设置动作。当用户点击按钮时,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];
    }
}

相关内容

  • 没有找到相关文章

最新更新