IOS:如何使用ios google drive sdk API下载Google Docs文件? [英] IOS: How to Download Google Docs files using ios google drive sdk API?
问题描述
我整合了谷歌drivs sdk与我的ios应用程序。目前我正在使用下面的代码从我的谷歌驱动器a / c下载文件的基础上下载url链接。但是,当我尝试下载谷歌文档文件(其中有MIME类型应用程序/ vnd.google-apps.document )时,谷歌驱动器库中没有下载URL链接。在那种情况下,我该如何下载谷歌文档数据?我可以使用 alternateLink 替代下载网址链接吗?任何帮助必须被赞赏。
我的代码:
code> - (void)loadFileContent {GTMHTTPFetcher * fetcher =
[self.driveService.fetcherService fetcherWithURLString:[[self.driveFiles objectAtIndex:selectedFileIdx] downloadUrl]];
[fetcher beginFetchWithCompletionHandler:^(NSData * data,NSError * error){
if(error == nil){
NSLog(@\\\
file%@ downloaded successfully从谷歌驱动器,[[self.driveFiles objectAtIndex:selectedFileIdx] originalFilename]);
//将下载的数据保存到临时位置
} else {
NSLog(@发生错误:%@,错误);
}
}];
}
第1步:
获取文件列表并存储它变成一个数组或字典与相关的文件下载链接url:
- (void)loadDriveFiles {
fileFetchStatusFailure = NO ;
//有关获取文件的更多信息,请查看此链接
//https://developers.google.com/drive/v2/reference/children/list
GTLQueryDrive * query2 = [GTLQueryDrive queryForChildrenListWithFolderId:[parentIdList lastObject]];
query2.maxResults = 1000;
// queryTicket可用于跟踪请求的状态。
[self.driveService executeQuery:query2
completionHandler:^(GTLServiceTicket * ticket,
GTLDriveChildList * children,NSError * error){
GTLBatchQuery * batchQuery = [GTLBatchQuery batchQuery];
//在此文件夹下没有文件,那么我们可以避免提取过程
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 child){
GTLQuery * query = [GTLQueryDrive queryForFilesGetWithFileId:child.identifier];
query.completionBlock = ^(GTLServiceTicket * ticket,GTLDriveFile * file,NSError * error){
//这个调用中的增量计数非常重要。因为执行查询调用是异步的
count ++;
NSLog(@Google Drive:检索儿童信息:%d,count);
if(error == nil){
if(file!= nil){//检查文件资源是否可用
//只添加文件信息,如果该文件不是在垃圾箱
if(file.labels.trashed.intValue!= 1)
[self addFileMetaDataInfo:file numberOfChilderns:totalChildren];
}
//进程传递所有文件,然后我们需要对检索到的文件进行排序
if(count == totalChildren){
NSLog(@Google Drive:处理所有孩子,现在停止HUDView - 1);
[self performSelectorOnMainThread:@selector(reloadTableDataFromMainThread)withObject:nil waitUntilDone:NO];
}
}其他{
//文件资源未找到
NSLog(@Google Drive:检索文件信息时发生错误:%@,错误);
if(count == totalChildren){
NSLog(@Google Drive:处理所有孩子,现在停止HUDView - 2);
[self performSelectorOnMainThread:@selector(reloadTableDataFromMainThread)
withObject:nil waitUntilDone:NO];
}
}
};
//将查询添加到批量查询中。因为我们不需要为每个孩子迭代google服务器。
[batchQuery addQuery:query];
}
//最后执行批量查询。由于文件检索过程要快得多,因为它会一次获得所有文件元数据信息
[self.driveService executeQuery:batchQuery
completionHandler:^(GTLServiceTicket * ticket,
GTLDriveFile * file,
NSError *错误){
}];
NSLog(@\\\
Google Drive:文件夹中的文件数量:%d,children.items.count);
}其他{
NSLog(@Google Drive:从父文件夹检索子列表时发生错误:%@,错误);
}
}];
}
第二步:
添加文件元数据信息
- (void)addFileMetaDataInfo:(GTLDriveFile *)文件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 {
//本地Google文档不存在文件下载网址。 Sicne我们可以设置导入文件MIME类型
//这里我们将MIME设置为pdf。由于我们可以下载文件内容,格式为pdf
if(!file.downloadUrl){
GTLDriveFileExportLinks * fileExportLinks;
NSString * exportFormat = @application / pdf;
fileExportLinks = [file exportLinks];
downloadURL = [fileExportLinks JSONValueForKey:exportFormat];
} else {
downloadURL = file.downloadUrl; (![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];
}
}
第3步:
下载文件基于表格中的文件选择行
NSString * downloadUrl = [[[[[[self.driveFiles objectAtIndex:selectedFileIdx] allValues] objectAtIndex :0]
objectAtIndex:download_url_link];
NSLog(@\\\
\\\
google驱动器文件下载url链接=%@,downloadUrl);
GTMHTTPFetcher * fetcher =
[self.driveService.fetcherService fetcherWithURLString:downloadUrl];
//异步调用来下载文件数据
[fetcher beginFetchWithCompletionHandler:^(NSData * data,NSError * error){
if(error == nil){
NSLog @\\\
file%@从谷歌驱动器成功下载,self.selectedFileName);
//将下载的数据保存到临时位置
[data writeToFile:< path>原子:YES];
} else {
NSLog(@发生错误:%@,错误);
}
}];
I integrated google drivs sdk with my ios app. At present am using the following code to download the files from my google drive a/c based on download url link. But when i try to download the google docs files (which has mime type application/vnd.google-apps.document) there is no download url link from google drive library. In that case how can i download the google docs data?. Can i use alternateLink instead of download url link?. Any help must be appreciated.
My Code:
- (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);
}
}];
}
Here the steps to download the file from google drive. It will work for both file and also google docs.
Step 1:
Fetch the file list and store it into an array or dict with related file download link 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: add the file metadata info
-(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: download the file based on file select on the table row
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);
}
}];
这篇关于IOS:如何使用ios google drive sdk API下载Google Docs文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!