2016-05-18 3 views
0

Мне нужно интегрировать почтовый ящик GMail в мое приложение после аутентификации. Так как я могу запросить содержимое почтового ящика GMail с помощью API. Кроме того, я также должен получить доступ к другим функциям. Поэтому, пожалуйста, помогите мне найти точный быстрый код для доступа к GMail.Как запросить содержимое почтового ящика GMail API GMail в Swift

ответ

0

с помощью Google Docs iOS Quickstart:

Шаг 1: Включите API Gmail

Шаг 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: Запустите образец

Примечание: информация авторизации хранятся в вашей брелке, так что последующий выполнение не потребует авторизации.

Вы можете просмотреть и узнать больше о iOS и API Google (API GMAIL) в https://developers.google.com/gmail/api/v1/reference/, чтобы применить другую функцию, которую вы хотите добавить.

Я надеюсь, что это помогает :)

+0

, но с помощью этого кода я получаю Gmail этикетки only.I уже пробовали эту code.I нужно получить содержимое в почтовом ящике, исходящие, отправить проект etc.can вас Помоги мне? –

+0

Вы пытались [использовать/запрашивать сообщения] (https://developers.google.com/gmail/api/guides/filtering)? После поиска используйте класс 'Users.messages: list', чтобы получить [сообщение] (https://developers.google.com/gmail/api/v1/reference/users/messages/list#response). –

Смежные вопросы