G. Tommy
G. Tommy

Reputation: 49

How download file google drive api ios

I tried to download file from google drive API since 3 day without success. I used this https://developers.google.com/drive/ios/devguide/files#reading_files.

But I can't understand what I need to put in *drive and *file?

I tried :
GTLDriveFile *file = @"fileText.txt"; (or I tried the url of my file on google drive...) The guide don't explain... And I didn't find real example.

GTLServiceDrive *drive = ...;
GTLDriveFile *file = ...;
NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media",
                          file.identifier]
GTMSessionFetcher *fetcher = [drive.fetcherService fetcherWithURLString:url];

[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  if (error == nil) {
    NSLog(@"Retrieved file content");
    // Do something with data
  } else {
    NSLog(@"An error occurred: %@", error);
  }
}];

So I had search other code like but no one explain what I need to put in drive and file:

  1. how to download file from google drive using objective c? (just this say it's url)
  2. Google drive api download file for iOS
  3. IOS: How to Download Google Docs files using ios google drive sdk API?

SOLUTION :

I had a problem of authorization with my scope, solved by total access to drive. I changed the scope (in quickstart code, look : "- (GTMOAuth2ViewControllerTouch *)createAuthController...") -->NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeDrive, nil];

For download (inspired by quickstart example) :

// self.service is my GTLServiceDrive

// 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) {
        // Not yet authorized, request authorization by pushing the login UI onto the UI stack.
        [self presentViewController:[self createAuthController] animated:YES completion:nil];
    } else {
        NSString *urltest = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media", identifier_file]; //the ID of my file in a string identifier_file
        GTMSessionFetcher *fetcher = [self.service.fetcherService fetcherWithURLString:urltest];  // the request
        // receive response and play it in web view:
        [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *errorrr) {
            if (errorrr == nil) {
                NSLog(@"Retrieved file content");
                [webView_screen loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil]; //my file is a pdf
                [webView_screen reload];
            } else {
                NSLog(@"An error occurred: %@", errorrr);
            }
        }];
    }
}

If you want to save on the phone, you can look the Bala's code.

Upvotes: 3

Views: 3926

Answers (1)

Bala
Bala

Reputation: 1304

First fetch the file from Drive

driveFiles = [[NSMutableArray alloc] init];
for (GTLDriveFile *file in files.items) {
    if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) {

    } else {
        NSString *fileExtension = file.fileExtension;
        if (fileExtension) {
            if ([fileExtension isEqualToString:@"pdf"]) {
                [driveFiles addObject:file];
            }
        }
    }
}

And GTLDriveFile pass the object that you have in the array

GTLDriveFile *file=[driveFiles objectAtIndex:indexPath.row];

This is the code for download the file

NSString *link;
if (file.webContentLink) {
    link = file.webContentLink;
} else if (file.embedLink) {
    link = file.embedLink;
} else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"File has no downloadable link" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
}

if (link) {
    NSString *downloadUrl = file.downloadUrl;
    GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadUrl];
    //async call to download the file data
    [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
        if (error == nil) {
            if (data) {
                NSString *dirPath = [self directoryPathForSavingFile];
                NSString *filePath = [dirPath stringByAppendingPathComponent:file.title];
                [self saveFileJSONData:data forFileName:filePath withCompletionHandler:^(BOOL successStatus) {
                    // Adding skip attribute to avoid data sinking in iCloud
                    BOOL path = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
                    if (path) {
                        NSLog(@"filePath %@", filePath);
                    }
                }];
            }
        } else {
            NSLog(@"An error occurred: %@", error);
        }
    }];
}

Code for Directory path for save the file

- (NSString *)directoryPathForSavingFile:(NSString *)directoryName {
    NSString *applicationDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    applicationDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
    return applicationDirectory;
}

Upvotes: 1

Related Questions