8 Mar 2017

Gmail API Integration iOS...



Gmail API Integration iOS...



Link:

https://developers.google.com/gmail/api/quickstart/ios



Add the below code in AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    NSString *userAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.23 (KHTML, like Gecko) Version/10.0 Mobile/14E5239e Safari/602";
    
    // set default useragent
    NSDictionary *dictionary = [[NSDictionary alloc]initWithObjectsAndKeys:userAgent,@"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:(dictionary)];
    
    return YES;

}

/************************************************************/



#import <UIKit/UIKit.h>

#import "GTMOAuth2ViewControllerTouch.h"
#import "GTLRGmail.h"

@interface ViewController : UIViewController

@property (nonatomic, strong) GTLRGmailService *service;
@property (nonatomic, strong) UITableView *output;
@property (nonatomic, strongNSString *checkLogout;


@end




#import "ViewController.h"
#import "GmailViewController.h"

static NSString *const kKeychainItemName = @"Gmail API";
static NSString *const kClientID = @"Add Your Client ID";

@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 = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.output.backgroundColor = [UIColor greenColor];
//    self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
    self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    // Initialize the Gmail API service & load existing credentials from the keychain if available.
    self.service = [[GTLRGmailService 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) || ([self.checkLogout isEqualToString:@"YES"])) {
        // Not yet authorized, request authorization by pushing the login UI onto the UI stack.
        [self presentViewController:[self createAuthController] animated:YES completion:nil];
        self.checkLogout=@"";
    } else {
//        [self fetchLabels];
        [self fetchMessages];
    }
}

// Construct a query and get a list of labels from the user's gmail. Display the
// label name in the UITextView
- (void)fetchLabels {
    GTLRGmailQuery_UsersLabelsList *query = [GTLRGmailQuery_UsersLabelsList queryWithUserId:@"me"];
//    query.fields = @"nextPageToken, files(id, name)";
    [self.service executeQuery:query
                      delegate:self
             didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}

- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
             finishedWithObject:(GTLRGmail_ListLabelsResponse *)labelsResponse
                          error:(NSError *)error {
    if (error == nil) {
        NSMutableString *labelString = [[NSMutableString alloc] init];
        NSMutableArray *arr=[NSMutableArray new];
        if (labelsResponse.labels.count > 0) {
//            [labelString appendString:@"Labels:\n"];
            
            for (GTLRGmail_Label *label in labelsResponse.labels) {
                
                [arr addObject:label];
                [labelString appendFormat:@"%@ (%@)\n", label.name, label.identifier];

                if(label==[labelsResponse.labels lastObject])
                {
                    GmailViewController *GMVC = [self.storyboard instantiateViewControllerWithIdentifier:@"GmailViewController"];
                    UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:GMVC];
                    GMVC.labelsArr=arr;
                    GMVC.service=self.service;
                    [self presentViewController:nav animated:YES completion:nil];
                }
            }
        } else {
            [labelString appendString:@"No labels found."];
            GmailViewController *GMVC = [self.storyboard instantiateViewControllerWithIdentifier:@"GmailViewController"];
            UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:GMVC];
            GMVC.labelsArr=arr;
            [self presentViewController:nav animated:YES completion:nil];
        }
    } else {
        [self showAlert:@"Error" message:error.localizedDescription];
    }
}

// Construct a query and get a list of labels from the user's gmail. Display the
// label name in the UITextView
- (void)fetchMessages {
    GTLRGmailQuery_UsersMessagesList *query = [GTLRGmailQuery_UsersMessagesList queryWithUserId:@"me"];
    //    query.fields = @"nextPageToken, files(id, name)";
    [self.service executeQuery:query
                      delegate:self
             didFinishSelector:@selector(displayMessagesResultWithTicket:finishedWithObject:error:)];
}

- (void)displayMessagesResultWithTicket:(GTLRServiceTicket *)ticket
             finishedWithObject:(GTLRGmail_ListMessagesResponse*)messagesResponse
                          error:(NSError *)error {
    if (error == nil) {
        NSMutableString *messageString = [[NSMutableString alloc] init];
        NSMutableArray *arr=[NSMutableArray new];
        if (messagesResponse.messages.count > 0) {
            
            for (GTLRGmail_Message *message in messagesResponse.messages) {
                
                [arr addObject:message];
                [messageString appendFormat:@"%@ (%@)\n", message.threadId, message.identifier];
                
                if(message==[messagesResponse.messages lastObject])
                {
                    GmailViewController *GMVC = [self.storyboard instantiateViewControllerWithIdentifier:@"GmailViewController"];
                    UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:GMVC];
                    GMVC.labelsArr=arr;
                    GMVC.service=self.service;
                    [self presentViewController:nav animated:YES completion:nil];
                }
            }
        } else {
            [messageString appendString:@"No messages found."];
            GmailViewController *GMVC = [self.storyboard instantiateViewControllerWithIdentifier:@"GmailViewController"];
            UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:GMVC];
            GMVC.labelsArr=arr;
            [self presentViewController:nav animated:YES completion:nil];
        }
    } 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:kGTLRAuthScopeGmailReadonly, 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 {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:title
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok =
    [UIAlertAction actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * action)
     {
         [alert dismissViewControllerAnimated:YES completion:nil];
     }];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
    
}

@end






#import <UIKit/UIKit.h>

#import "GTMOAuth2ViewControllerTouch.h"
#import "GTLRGmail.h"

@interface GmailViewController : UIViewController


@property (nonatomic, strong) GTLRGmailService *service;
@property (nonatomic,strong)NSMutableArray *labelsArr;

@end




#import "GmailViewController.h"
#import "ViewController.h"

@interface GmailViewController ()

@end

@implementation GmailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [ self.navigationController.navigationBar setBarTintColor : [UIColor whiteColor]];
    [self showbackButton];
    
}

-(void)showbackButton
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"LogOut" style:UIBarButtonItemStylePlain target:self action:@selector(logoutButtonClicked:)];
}

-(void)logoutButtonClicked:(id)sender
{
    ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
    vc.checkLogout=@"YES";
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(self.labelsArr.count>0) {
        return [self.labelsArr count];
    }else {
        return 1;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if(self.labelsArr.count>0){
//        GTLRGmail_Label *label = [self.labelsArr objectAtIndex:indexPath.row];
        
        GTLRGmail_Message *message = [self.labelsArr objectAtIndex:indexPath.row];
        
        cell.textLabel.text = message.threadId;
//        cell.textLabel.text=label.name;
    } else {
        cell.textLabel.text=@"No labels found..";
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    GTLRGmail_Label *label = [self.labelsArr objectAtIndex:indexPath.row];
    GTLRGmail_Message *message = [self.labelsArr objectAtIndex:indexPath.row];
    
//    NSLog(@"....>> %@",label.identifier);
    
    NSString *URL = [NSString stringWithFormat:@"https://www.googleapis.com/gmail/v1/users/me/messages/%@",message.identifier];
//    NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/gmail/v1/users/me/labels/%@",label.identifier];

    GTMSessionFetcher *fetcher = [self.service.fetcherService fetcherWithURLString:URL];
    
    [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
        if (error == nil) {
        
            NSString *dataStr =   [data base64EncodedStringWithOptions:0];
            
              NSLog(@"Datastr--->> %@", dataStr);
            
            NSData *nsdataFromBase64String = [[NSData alloc]
                                              initWithBase64EncodedString:dataStr options:0];
            
            // Decoded NSString from the NSData
            NSString *base64Decoded = [[NSString alloc]
                                       initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
            NSLog(@"Decoded: %@", base64Decoded);
            NSString *path = [[self applicationDocumentsDirectory].path
                              stringByAppendingPathComponent:@"fileName.txt"];
            
            NSLog(@"Datastr--->> %@", dataStr);
            
            [base64Decoded writeToFile:path atomically:YES
                              encoding:NSUTF8StringEncoding error:nil];
            
            NSError *error;
            NSString *fileContents2 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
            
            if (error)
                NSLog(@"Error reading file: %@", error.localizedDescription);
            
            // maybe for debugging...
            NSLog(@"contents: %@", fileContents2);
            
            NSURL *url = [NSURL fileURLWithPath:path];
            NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
            
            UIWebView *webView=[[UIWebView alloc]initWithFrame:CGRectMake(5, 65, self.view.frame.size.width, self.view.frame.size.height)];
            
            [webView setUserInteractionEnabled:YES];
            //                 [webView setDelegate:self];
            [webView loadRequest:requestObj];
            [self.view addSubview:webView];
            
            NSLog(@"Retrieved label content-------- %@",dataStr);
        } else {
            NSLog(@"An error occurred: %@", error);
        }
    }];
    
}

- (void)myFetcher:(GTMSessionFetcher *)fetcher receivedData:(NSData *)dataReceivedSoFar
{
    NSLog(@"%@ ",dataReceivedSoFar);
}

- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                   inDomains:NSUserDomainMask] lastObject];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end






No comments:

Post a Comment

Recent Posts

Codable demo

Link: https://www.dropbox.com/s/kw7c1kgv1628bh7/codableDemo.zip?dl=0