【问题标题】:How to query the inbox content of GMail by GMail API in Swift如何在 Swift 中通过 GMail API 查询 GMail 的收件箱内容
【发布时间】:2016-09-14 16:15:19
【问题描述】:

我需要在认证后将GMail收件箱集成到我的应用程序中。那么如何使用API​​查询GMail的收件箱内容。而且我也必须访问其他功能。所以请帮助我找到访问 GMail 的确切 swift 代码。

【问题讨论】:

    标签: ios swift gmail-api google-api-client gtm-oauth2


    【解决方案1】:

    使用谷歌文档iOS Quickstart

    第 1 步:开启 Gmail API

    第 2 步:准备工作区

    第 3 步:设置示例

    这里是一个示例代码,将ViewController.h文件的内容替换为以下代码:

    #import <UIKit/UIKit.h>
    
    #import "GTMOAuth2ViewControllerTouch.h"
    #import "GTLGmail.h"
    
    @interface ViewController : UIViewController
    
    @property (nonatomic, strong) GTLServiceGmail *service;
    @property (nonatomic, strong) UITextView *output;
    
    @end
    

    ViewController.m的内容替换为以下代码:

    #import "ViewController.h"
    
    static NSString *const kKeychainItemName = @"Gmail API";
    static NSString *const kClientID = @"YOUR_CLIENT_ID_HERE";
    
    @implementation ViewController
    
    @synthesize service = _service;
    @synthesize output = _output;
    
    // When the view loads, create necessary subviews, and initialize the Gmail API service.
    - (void)viewDidLoad {
      [super viewDidLoad];
    
      // Create a UITextView to display output.
      self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
      self.output.editable = false;
      self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
      self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
      [self.view addSubview:self.output];
    
      // Initialize the Gmail API service & load existing credentials from the keychain if available.
      self.service = [[GTLServiceGmail alloc] init];
      self.service.authorizer =
      [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                            clientID:kClientID
                                                        clientSecret:nil];
    }
    
    // When the view appears, ensure that the Gmail API service is authorized, and perform API calls.
    - (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];
    
      } else {
        [self fetchLabels];
      }
    }
    
    // Construct a query and get a list of labels from the user's gmail. Display the
    // label name in the UITextView
    - (void)fetchLabels {
      self.output.text = @"Getting labels...";
      GTLQueryGmail *query = [GTLQueryGmail queryForUsersLabelsList];
      [self.service executeQuery:query
                        delegate:self
               didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
    }
    
    - (void)displayResultWithTicket:(GTLServiceTicket *)ticket
                 finishedWithObject:(GTLGmailListLabelsResponse *)labelsResponse
                              error:(NSError *)error {
      if (error == nil) {
        NSMutableString *labelString = [[NSMutableString alloc] init];
        if (labelsResponse.labels.count > 0) {
          [labelString appendString:@"Labels:\n"];
          for (GTLGmailLabel *label in labelsResponse.labels) {
            [labelString appendFormat:@"%@\n", label.name];
          }
        } else {
          [labelString appendString:@"No labels found."];
        }
        self.output.text = labelString;
      } else {
        [self showAlert:@"Error" message:error.localizedDescription];
      }
    }
    
    
    // Creates the auth controller for authorizing access to Gmail 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;
    }
    
    // Handle completion of the authorization process, and update the Gmail API
    // with the new credentials.
    - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
          finishedWithAuth:(GTMOAuth2Authentication *)authResult
                     error:(NSError *)error {
      if (error != nil) {
        [self showAlert:@"Authentication Error" message:error.localizedDescription];
        self.service.authorizer = nil;
      }
      else {
        self.service.authorizer = authResult;
        [self dismissViewControllerAnimated:YES completion:nil];
      }
    }
    
    // Helper for showing an alert
    - (void)showAlert:(NSString *)title message:(NSString *)message {
      UIAlertView *alert;
      alert = [[UIAlertView alloc] initWithTitle:title
                                         message:message
                                        delegate:nil
                               cancelButtonTitle:@"OK"
                               otherButtonTitles:nil];
      [alert show];
    }
    
    @end
    

    第 4 步:运行示例

    注意事项:授权信息存储在您的 Keychain 中,因此后续执行不会提示授权。

    您可以在https://developers.google.com/gmail/api/v1/reference/ 中查看和了解有关 iOS 和 Google API(GMAIL API)的更多信息,以应用您想要添加的其他功能。

    我希望这会有所帮助:)

    【讨论】:

    • 但是通过使用此代码,我只能获取 gmail 标签。我已经尝试过此代码。我需要获取收件箱、发件箱、发送、草稿等中的内容。你能帮帮我吗?跨度>
    • 你试过using/querying for the messages吗?搜索完后,使用Users.messages: list类得到message
    猜你喜欢
    • 2019-04-29
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2017-09-02
    • 2020-05-21
    相关资源
    最近更新 更多