【问题标题】:Get access token for gmail api via objective-c通过objective-c获取gmail api的访问令牌
【发布时间】:2016-11-30 18:07:12
【问题描述】:

我使用了来自this sample 的代码。要获取用户未读消息的数量(这就是我需要的),我需要发送这个GET 请求

https://www.googleapis.com/gmail/v1/users/me/labels/UNREAD?key={MY_API_KEY}

喜欢this example。但我想{ACCESS_TOKEN} 应该在这里而不是{MY_API_KEY}。如果是这样,谁能告诉我如何使用 AFNetworking 或 auth from the sample 获取访问令牌?

【问题讨论】:

    标签: ios objective-c gmail afnetworking gmail-api


    【解决方案1】:

    Authorizing Your App with Gmail中所述

    Gmail 使用 OAuth 2.0 protocol 来验证 Google 帐户并授权访问用户数据。您还可以使用Google+ Sign-in 为您的应用提供“使用 Google 登录”身份验证方法。

    如果按照要求使用 AFNetworking 仍然是您的偏好,您可以使用关于如何获取此 GitHub 帖子中给出的访问令牌的指南 - AFOAuth2Manager

    此 SO 帖子中给出的解决方案 - How to get the number of unread threads in INBOX with Gmail API 也可能有所帮助。

    【讨论】:

    • 根据我向用户提供 Google 登录的示例,但在授权请求后仍然 https://www.googleapis.com/gmail/v1/users/me/labels/UNREAD?key={MY_API_KEY} 给我一个错误:请求失败:未授权 (401)
    【解决方案2】:

    要获取访问令牌以向 Google API 发出授权请求,您应该实现以下方法:

    - (GTMOAuth2ViewControllerTouch *)createAuthController {
    GTMOAuth2ViewControllerTouch *authController;
    // If modifying these scopes, delete your previously saved credentials by
    // resetting the iOS simulator or uninstall the app.
    NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeGmailReadonly, nil];
    authController = [[GTMOAuth2ViewControllerTouch alloc]
                      initWithScope:[scopes componentsJoinedByString:@" "]
                      clientID:kClientID
                      clientSecret:nil
                      keychainItemName:kKeychainItemName
                      delegate:self
                      finishedSelector:@selector(viewController:finishedWithAuth:error:)];
    return authController;
    }
    
    
    - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuth2Authentication *)authResult
                 error:(NSError *)error {
    if (error != nil) {
       ...
    }
    else {
        NSLog(@"Access token: %@", authResult.accessToken);
    
     }
    }
    

    您的 ViewDidAppear 方法应如下所示:

    - (void)viewDidAppear:(BOOL)animated {
    if (!self.service.authorizer.canAuthorize) {
        // Not yet authorized, request authorization by pushing the login UI onto the UI stack.
        [self presentViewController:[self createAuthController] animated:YES completion:nil];
    }
    

    该代码输出目标访问令牌。

    【讨论】:

      猜你喜欢
      • 2016-12-13
      • 2016-07-12
      • 2012-06-19
      • 1970-01-01
      • 2016-12-27
      • 2017-12-10
      • 2018-12-27
      • 1970-01-01
      • 2016-08-28
      相关资源
      最近更新 更多