cannot download file from google drive in ios

寵の児 提交于 2019-12-23 16:48:24

问题


I am very new to IOS development, I am developing an app in which I want to download a file from Google Drive (pdf,doxc,doc and xlxs) and which will be sent to sent it to our server.

First I have installed it in pod file by using

pod 'GoogleAPIClient/Drive', '~> 1.0.2'
pod 'GTMOAuth2', '~> 1.1.0'

Second I created a project in Google Developer Console with bundle id and got client id, I have saved it into my project.

When user clicks select file button

-(IBAction)onclickfileFromDrive:(id)sender
{

    self.service = [[GTLServiceDrive alloc] init];
    self.service.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kClientID clientSecret:nil];
    NSLog(@"service reply%hhd",self.service.authorizer.canAuthorize);
    if (!self.service.authorizer.canAuthorize)
    {

        [self presentViewController:[self createAuthController] animated:YES completion:nil];
    }
    else
    {
        [self fetchFiles];
    }
}



- (GTMOAuth2ViewControllerTouch *)createAuthController
{
    GTMOAuth2ViewControllerTouch *authController;

    NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeDrive, nil];
    authController = [[GTMOAuth2ViewControllerTouch alloc]
                      initWithScope:[scopes componentsJoinedByString:@" "]
                      clientID:kClientID
                      clientSecret:nil
                      keychainItemName:kKeychainItemName
                      delegate:self
                      finishedSelector:@selector(viewController:finishedWithAuth:error:)];
    return authController;
}
- (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];
    }
    self.service.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kClientID clientSecret:nil];
    NSLog(@"service reply%hhd",self.service.authorizer.canAuthorize);
    if (self.service.authorizer.canAuthorize)
    {
        [self fetchFiles];
    }
}

The process of login is working fine here I am getting access token and refresh token

while I am trying to download a file

    - (void)fetchFiles
        {
            GTLQueryDrive *query =[GTLQueryDrive queryForFilesList];
            query.q = @"mimeType ='application/pdf' or mimeType ='text/plain' or mimeType ='application/msword' or mimeType ='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' or mimeType =  'application/vnd.openxmlformats-officedocument.wordprocessingml.document'";
            [self.service executeQuery:query delegate:self didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];

        }

- (void)displayResultWithTicket:(GTLServiceTicket *)ticket finishedWithObject:(GTLDriveFileList *)response error:(NSError *)error
{
    if (error == nil)
    {
        NSMutableString *filesString = [[NSMutableString alloc] init];
        if (response.files.count > 0)
        {
            for (GTLDriveFile *file in response.files)
            {
                [filesString appendFormat:@"%@ (%@)\n", file.name, file.identifier];

                NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?key=%@", file.identifier,kClientID];

                GTMSessionFetcher *fetcher = [_service.fetcherService fetcherWithURLString:url];

                [fetcher beginFetchWithCompletionHandler:^(NSData *datav, NSError *error)
                 {
                     if (error == nil)
                     {
                         NSLog(@" file web link%@",file.webViewLink);
                         NSLog(@"file extension%@",file.fileExtension);

                         NSLog(@"Retrieved file content%@",datav);

                         NSString *prefixString = @"EMR File";
                         NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString] ;
                         NSString *uniqueFileName = [NSString stringWithFormat:@"%@_%@", prefixString, guid];
                         NSString  *filePath = [[NSString alloc]init];

                         /***************** save the file in document directory ***********************/

                         if (datav!=nil)
                         {

                             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

                             //Get the docs directory

                             NSString *documentsDirectoryPath = [paths objectAtIndex:0];

                             NSString *folderPath = [documentsDirectoryPath  stringByAppendingPathComponent:@"emrFiles"];  // subDirectory

                             if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])

                                 [[NSFileManager defaultManager] createDirectoryAtPath:folderPath  withIntermediateDirectories:NO attributes:nil error:nil];



                             //Add the FileName to FilePath

                             filePath = [folderPath stringByAppendingPathComponent:[uniqueFileName   stringByAppendingFormat:@".%@",file.fileExtension]];

                             //Write the file to documents directory

                             [datav writeToFile:filePath atomically:YES];
                         }


                     }
                     else
                     {
                         NSLog(@"An error occurred: %@", error.localizedDescription);
                     }
                 }];
            }
        }
        else
        {
            [filesString appendString:@"No files found."];
        }
    }
    else
    {
        [self showAlert:@"Error" message:error.localizedDescription];
    }
}

the file details like

NSLog(@" file web link%@",file.webViewLink);
NSLog(@"file extension%@",file.fileExtension);
file.fileExtension

These are getting null in all the time

However I am getting value for

file.name
file.identifier

Finally if I try to download a file using this url

NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?key=%@", file.identifier,kClientID];

and

NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?key=My API key from google console",
                     myfile.identifier];

I am getting nsdata very small content

Printing description of datav:

<7b0a2022 6b696e64 223a2022 64726976 65236669 6c65222c 0a202269 64223a20 22304236 6a6e576c 46497868 434f566e 6c586546 4a496344 526d596d 68694e44 6c735432 557a516b 7057566c 70716431 5246222c 0a20226e 616d6522 3a202253 41544859 412e646f 6378222c 0a20226d 696d6554 79706522 3a202261 70706c69 63617469 6f6e2f76 6e642e6f 70656e78 6d6c666f 726d6174 732d6f66 66696365 646f6375 6d656e74 2e776f72 6470726f 63657373 696e676d 6c2e646f 63756d65 6e74220a 7d0a>

Because of getting null value of file extension I tried with giving static extension and saved it in directory and try to view it and I get this error

“ File_B85DABFF-BCA5-4B5E-8FDC-59D2907F0509-1053-000003B0E6E4C9A9.docx” can’t be opened for some reason.

I don't know that where I am lacking I have searched more but could not help please any one help me on this

thanks in advance

来源:https://stackoverflow.com/questions/40233330/cannot-download-file-from-google-drive-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!