5

我将 google 驱动 sdk 与我的 ios 应用程序集成在一起。目前我正在使用以下代码根据下载 url 链接从我的谷歌驱动器 a/c 下载文件。但是当我尝试下载谷歌文档文件(具有 mime 类型application/vnd.google-apps.document)时,谷歌驱动库中没有下载 url 链接。在那种情况下,我如何下载谷歌文档数据?我可以使用alternateLink而不是下载网址链接吗?必须感谢任何帮助。

我的代码:

- (void)loadFileContent {

GTMHTTPFetcher *fetcher =
[self.driveService.fetcherService fetcherWithURLString:[[self.driveFiles objectAtIndex:selectedFileIdx] downloadUrl]];

[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
    if (error == nil) {
        NSLog(@"\nfile %@ downloaded successfully from google drive", [[self.driveFiles objectAtIndex:selectedFileIdx] originalFilename]);

        //saving the downloaded data into temporary location

    } else {
        NSLog(@"An error occurred: %@", error);            

    }
}];

}

4

3 回答 3

5

这里是从谷歌驱动器下载文件的步骤。它适用于文件和谷歌文档。

步骤1:

获取文件列表并将其存储到具有相关文件下载链接 url 的数组或字典中:

- (void)loadDriveFiles {
fileFetchStatusFailure = NO;

//for more info about fetching the files check this link
//https://developers.google.com/drive/v2/reference/children/list    
GTLQueryDrive *query2 = [GTLQueryDrive queryForChildrenListWithFolderId:[parentIdList lastObject]];
query2.maxResults = 1000;

// queryTicket can be used to track the status of the request.
[self.driveService executeQuery:query2
              completionHandler:^(GTLServiceTicket *ticket,
                                  GTLDriveChildList *children, NSError *error) {
                  GTLBatchQuery *batchQuery = [GTLBatchQuery batchQuery];                      
                  //incase there is no files under this folder then we can avoid the fetching process
                  if (!children.items.count) {                          
                      [self.driveFiles removeAllObjects];
                      [fileNames removeAllObjects];                          
                      [self performSelectorOnMainThread:@selector(reloadTableDataFromMainThread) withObject:nil waitUntilDone:NO];                          
                      return ;
                  }

                  if (error == nil) {
                      int totalChildren = children.items.count;
                      count = 0;

                      [self.driveFiles removeAllObjects];
                      [fileNames removeAllObjects];                                                    //http://stackoverflow.com/questions/14603432/listing-all-files-from-specified-folders-in-google-drive-through-ios-google-driv/14610713#14610713
                      for (GTLDriveChildReference *child in children) {
                          GTLQuery *query = [GTLQueryDrive queryForFilesGetWithFileId:child.identifier];                              
                          query.completionBlock = ^(GTLServiceTicket *ticket, GTLDriveFile *file, NSError *error) {

                              //increment count inside this call is very important. Becasue the execute query call is asynchronous
                              count ++;
                              NSLog(@"Google Drive: retrieving children info: %d", count);                                  
                              if (error == nil) {
                                  if (file != nil) { //checking the file resource is available or not
                                      //only add the file info if that file was not in trash
                                      if (file.labels.trashed.intValue != 1 )
                                          [self addFileMetaDataInfo:file numberOfChilderns:totalChildren];
                                  }

                                  //the process passed all the files then we need to sort the retrieved files
                                  if (count == totalChildren) {
                                      NSLog(@"Google Drive: processed all children, now stopping HUDView - 1");
                                      [self performSelectorOnMainThread:@selector(reloadTableDataFromMainThread) withObject:nil waitUntilDone:NO];
                                  }
                              } else {
                                  //the file resource was not found
                                  NSLog(@"Google Drive: error occurred while retrieving file info: %@", error);

                                  if (count == totalChildren) {
                                      NSLog(@"Google Drive: processed all children, now stopping HUDView - 2");
                                      [self performSelectorOnMainThread:@selector(reloadTableDataFromMainThread)
                                                             withObject:nil waitUntilDone:NO];
                                  }                                      
                              }                                  
                          };                              
                          //add the query into batch query. Since we no need to iterate the google server for each child.
                          [batchQuery addQuery:query];
                      }                          
                      //finally execute the batch query. Since the file retrieve process is much faster because it will get all file metadata info at once
                      [self.driveService executeQuery:batchQuery
                                    completionHandler:^(GTLServiceTicket *ticket,
                                                        GTLDriveFile *file,
                                                        NSError *error) {
                                    }];

                      NSLog(@"\nGoogle Drive: file count in the folder: %d", children.items.count);
                  } else {
                      NSLog(@"Google Drive: error occurred while retrieving children list from parent folder: %@", error);
                  }
              }];

}

step-2:添加文件元数据信息

    -(void)addFileMetaDataInfo:(GTLDriveFile*)file numberOfChilderns:(int)totalChildren
{
    NSString *fileName = @"";
    NSString *downloadURL = @"";

    BOOL isFolder = NO;

    if (file.originalFilename.length)
        fileName = file.originalFilename;
    else
        fileName = file.title;

    if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) {
        isFolder = YES;
    } else {
        //the file download url not exists for native google docs. Sicne we can set the import file mime type
        //here we set the mime as pdf. Since we can download the file content in the form of pdf
        if (!file.downloadUrl) {
            GTLDriveFileExportLinks *fileExportLinks;

            NSString    *exportFormat = @"application/pdf";

            fileExportLinks = [file exportLinks];
            downloadURL = [fileExportLinks JSONValueForKey:exportFormat];
        } else {
            downloadURL = file.downloadUrl;
        }
    }

    if (![fileNames containsObject:fileName]) {
        [fileNames addObject:fileName];

        NSArray *fileInfoArray = [NSArray arrayWithObjects:file.identifier, file.mimeType, downloadURL,
                                  [NSNumber numberWithBool:isFolder], nil];
        NSDictionary *dict = [NSDictionary dictionaryWithObject:fileInfoArray forKey:fileName];

        [self.driveFiles addObject:dict];
    }
}

step-3:根据表格行上的文件选择下载文件

    NSString *downloadUrl = [[[[self.driveFiles objectAtIndex:selectedFileIdx] allValues] objectAtIndex:0]
                   objectAtIndex:download_url_link];
NSLog(@"\n\ngoogle drive file download url link = %@", downloadUrl);    
GTMHTTPFetcher *fetcher =
[self.driveService.fetcherService fetcherWithURLString:downloadUrl];    
//async call to download the file data
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
    if (error == nil) {
        NSLog(@"\nfile %@ downloaded successfully from google drive", self.selectedFileName);

        //saving the downloaded data into temporary location
        [data writeToFile:<path> atomically:YES];               
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];
于 2014-01-02T09:03:52.207 回答
3

Google Docs 原生格式的文档不能作为其他文件下载,只能使用exportLinksURL 导出为不同的支持格式。

有关更多详细信息和支持的格式列表,请查看 Google Drive SDK 文档:

https://developers.google.com/drive/manage-downloads#downloading_google_documents

于 2012-11-20T02:30:26.013 回答
1

我以前也有类似的问题。具体来说,我没有找到在 Google Document 中创建的原生文档的 downloadurl。它们是空的。只有通过 DrEdit 创建的(Drive SDK 中举例说明的解决方案)与 downloadUrl 相关联。

解决方案实际上是嵌入到属性中: GTLDriveFileExportLinks实例中的JSON,它返回 NSMutableDictionary*。您可以选择通过访问JSONString属性来查看 JSON 对象的内容。JSON可变字典可以通过查询GTLDriveFile实例中的exportLinks得到。示例如下:

GTLDriveFile *file = files.items[0]; // assume file is assigned to a valid instance.
NSMutableDictionary *jsonDict = file.exportLinks.JSON; 
NSLog(@"URL:%@.", [jsonDict objectForKey:@"text/plain"]);
于 2013-10-01T13:10:06.857 回答