8 Mar 2017

Google Drive API Integration iOS...



Google Drive API Integration iOS...

First see the link below Once...

Link:

https://developers.google.com/drive/v3/web/quickstart/ios



@implementation AppDelegate


- (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 "GTLRDrive.h"

@interface ViewController : UIViewController

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

@end



#import "ViewController.h"
#import "FilesViewController.h"

static NSString *const kKeychainItemName = @"Drive API";
static NSString *const kClientID = @"ADD Client ID";

@implementation ViewController

@synthesize service = _service;
@synthesize output = _output;

// When the view loads, create necessary subviews, and initialize the Drive 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 Drive API service & load existing credentials from the keychain if available.
    self.service = [[GTLRDriveService alloc] init];
    self.service.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                          clientID:kClientID
                                                      clientSecret:nil];
}

// When the view appears, ensure that the Drive 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 listFiles];
    }
}

// List up to 20 files in Drive
- (void)listFiles {
    GTLRDriveQuery_FilesList *query = [GTLRDriveQuery_FilesList query];
    query.fields = @"nextPageToken, files(id, name)";
    query.pageSize = 20;
    
    [self.service executeQuery:query
                      delegate:self
             didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}

// Process the response and display output
- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
             finishedWithObject:(GTLRDrive_FileList *)result
                          error:(NSError *)error {
    if (error == nil) {
        NSMutableString *filesString = [[NSMutableString alloc] init];
        NSMutableArray *arr=[NSMutableArray new];
        if (result.files.count > 0) {
//            [output appendString:@"Files:\n"];
    
            for (GTLRDrive_File *file in result.files) {
                
                 [arr addObject:file];
                [filesString appendFormat:@"%@ (%@)\n", file.name, file.identifier];
                if(file==[result.files lastObject])
                {
                    FilesViewController *fvc=[self.storyboard instantiateViewControllerWithIdentifier:@"FilesViewController"];
                    UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:fvc];
                    fvc.filesArr=arr;
                    fvc.service=self.service;
                    [self presentViewController:nav animated:YES completion:nil];
                }
            }
        } else {
            FilesViewController *fvc=[self.storyboard instantiateViewControllerWithIdentifier:@"FilesViewController"];
            UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:fvc];
            fvc.filesArr=arr;
            
            [self presentViewController:nav animated:YES completion:nil];
        }
    } else {
        NSMutableString *message = [[NSMutableString alloc] init];
        [message appendFormat:@"Error getting presentation data: %@\n", error.localizedDescription];
        [self showAlert:@"Error" message:message];
    }
}

// Creates the auth controller for authorizing access to Drive 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:kGTLRAuthScopeDriveReadonly, 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 Drive 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 "GTLRDrive.h"

@interface FilesViewController : UIViewController

@property (nonatomic, strong) GTLRDriveService *service;
@property (nonatomic,strong)NSMutableArray *filesArr;

@end

#import "FilesViewController.h"

#import "ViewController.h"

@interface FilesViewController ()

@end

@implementation FilesViewController

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

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

-(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];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(self.filesArr.count>0){
        return [self.filesArr 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.filesArr.count>0){
        GTLRDrive_File *file=[self.filesArr objectAtIndex:indexPath.row];
        
        cell.textLabel.text=file.name;
    } else {
        cell.textLabel.text=@"No files found..";
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GTLRDrive_File *file=[self.filesArr objectAtIndex:indexPath.row];
    
    NSLog(@"....>> %@",file.identifier);
    
    NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@/export?alt=media&mimeType=application/pdf", file.identifier];
    GTMSessionFetcher *fetcher = [self.service.fetcherService fetcherWithURLString:url];
    
    [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
        if (error == nil) {

            NSString *dataStr =   [data base64EncodedStringWithOptions:0];      
            
            NSString *path = [[self applicationDocumentsDirectory].path
                              stringByAppendingPathComponent:@"fileName.txt"];
            
            NSLog(@"Datastr--->> %@", dataStr);

            [dataStr 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(0, 0, 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 file 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