7

我从 Google 找到了一项服务,可以访问Google APIs各种 Google 服务。我可以在 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];
}
4

3 回答 3

2

首先,您需要从 Google API 获取令牌,对于这第一步,您必须遵循本教程,在此链接的末尾有用于从 google API 获取令牌的 iOS 的完整源代码

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

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

于 2014-01-11T20:38:59.740 回答
1

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

..这对我来说很好。

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

于 2014-01-10T10:14:21.107 回答
0

我认为这将帮助其他任何人按照以下步骤将 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 中选择项目和目标。在目标“Build Phases”选项卡下,展开 Compile Sources 构建阶段,选择库源文件,然后按 Enter 打开编辑字段,并键入 -fno-objc-arc 作为这些文件的编译器标志。

2.添加以下框架

security.framework , systemConfiguration.framework

3. 将您的应用注册到 google 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];

    }
}
于 2014-07-08T10:56:24.117 回答