ios - 如何下载文件google drive api ios

标签 ios objective-c google-drive-api

3 天后我尝试从 google drive API 下载文件但没有成功。我用了这个 https://developers.google.com/drive/ios/devguide/files#reading_files .

但我不明白我需要在 *drive 和 *file 中放些什么?

我试过了:
GTLDriveFile *file = @"fileText.txt";(或者我在谷歌驱动器上尝试了我的文件的 url...)指南没有解释...而且我没有找到真正的示例。

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

所以我搜索了其他代码,但没有人解释我需要放入驱动器和文件中的内容:

  1. how to download file from google drive using objective c? (只是这个说它是 url)
  2. Google drive api download file for iOS
  3. IOS: How to Download Google Docs files using ios google drive sdk API?

解决方案:

我的范围有授权问题,通过完全访问驱动器解决了。我更改了范围(在快速入门代码中,看:“- (GTMOAuth2ViewControllerTouch *)createAuthController...”) -->NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeDrive, nil];

下载(受快速入门示例启发):

// 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);
            }
        }];
    }
}

如果你想在手机上省钱,你可以看看巴拉的代码。

最佳答案

首先从云端硬盘中获取文件

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

GTLDriveFile 传递数组中的对象

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

这是下载文件的代码

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

保存文件的目录路径代码

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

关于ios - 如何下载文件google drive api ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974226/

相关文章:

ios - TabView SwiftUI 中 TabItem 上的 LinearGradient

ios - 将自定义 UITableViewCell 内容与标题对齐

objective-c - Tableview 图片加载缓慢

objective-c - KVO for one-to-many but NSNull object passed into observeValueForKeyPath

c# - 如何以编程方式从 Google 云端硬盘中的 "share with me"中删除文件

javascript - 谷歌驱动器范围 'Error Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.'

ios - iOS 中的日历控件

ios - 双括号是什么意思?

javascript - 如何使用 javascript 播放 google drive video?

iOS( swift ): Collection View indexPath(for: cell) is nil for non visible cell