IOS: ¿Cómo download files de Google Docs usando ios google drive sdk API?

Integré google drivs sdk con mi aplicación ios. Actualmente estoy usando el siguiente código para download los files de mi google drive a / c basado en el enlace de la URL de descarga. Pero cuando bash download los files de google docs (que tiene la aplicación de tipo mime / vnd.google-apps.document ) no hay un enlace de descarga de url de la biblioteca de Google Drive. En ese caso, ¿cómo puedo download los datos de google docs ?. ¿Puedo usar alternateLink en lugar de download url link ?. Cualquier ayuda debe ser apreciada.

Mi código:

- (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 occurnetworking: %@", error); } }]; 

}

Aquí los pasos para download el file de Google Drive. Funcionará tanto para el file como para Google Docs.

Paso 1:

Obtenga la list de files y guárdela en una matriz o dict con la URL relacionada del enlace de descarga de files relacionados:

 - (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 occurnetworking 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 occurnetworking while retrieving children list from parent folder: %@", error); } }]; 

}

paso 2: agregue la información de metadatos del file

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

paso 3: descarga el file basado en la selección de file en la fila de la tabla

  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 occurnetworking: %@", error); } }]; 

Los documentos en los formattings nativos de Google Docs no pueden downloadse como otros files, sino que solo se exportan a diferentes formattings compatibles utilizando las URL de exportLinks .

Para get más detalles y la list de formattings compatibles, consulte la documentation del SDK de Google Drive:

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

Tuve un problema similar antes. Específicamente, no encontré downloadurl para los documentos nativos creados en el documento de Google. Son nulas Solo aquellos creados mediante DrEdit (soluciones ejemplificadas en Drive SDK) están asociados con downloadUrl.

La solución está realmente incrustada en el atributo: JSON en la instancia GTLDriveFileExportLinks , que devuelve NSMutableDictionary *. Puede optar por ver el contenido del object JSON mediante el acceso al atributo JSONString . El dictionary mutable JSON se puede get mediante la consulta de exportLinks en la instancia GTLDriveFile . El ejemplo es el siguiente:

 GTLDriveFile *file = files.items[0]; // assume file is assigned to a valid instance. NSMutableDictionary *jsonDict = file.exportLinks.JSON; NSLog(@"URL:%@.", [jsonDict objectForKey:@"text/plain"]);