Google 在 iOS 中驱动 REST

Google Drive REST in iOS

我的问题很简单。 集成 Google Drive REST API 我终于可以从我的 Google 下载文件 Drive.SO 我已经按照这个例子 https://developers.google.com/drive/v3/web/manage-downloads 一切正常,在控制台中我得到文件已下载的信息。所以这里是 question:where 它去了哪个文件夹?保存文件的路径是什么? 如果我需要将文件保存到 iOS Documents 文件夹,如何设置必要的保存路径?

NSString *fileId = @"0BwwA4oUTeiV1UVNwOHItT0xfa2M";

GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDataObject *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

我正在为 iOS 10 及更高版本开发,当我阅读 infrmation:NOTE 时:因为从 iOS 9 和 OS X 10.11 开始不推荐使用 NSURLConnection,此 class 已被 GTMSessionFetcher.I 取代,应使用 google(在上面发布)提供的代码或 GTMSessionFetcher.I 我正在使用 google.But 的代码 将不胜感激将帮助我解决(google 和 GTMSessionFetcher)变体的问题。

UPD:对于 Google API 客户端库

GTLRDataObjectdata 属性,其中包含文件的原始字节。使用标准 iOS 方法来保护您的文件就足够了。

还有contentType 属性是文件的MIME type的字符串。您可能希望将此信息与保存路径一起存储在某处 data,这将帮助您正确显示文件类型 (image/song/text),并在您 decode/open/read 保存数据以呈现实际信息。

GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                 GTLRDataObject *file,
                                                 NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);

        // Here is where you take these bytes and save them as file to any location you want (typically your Documents folder)
        NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        [file.data writeToURL:documentsDirectoryURL atomically:YES];

        // Now you can store the url/path of the saved file somewhere along with the MIME type string (maybe new class or structure describing the file in your app)
        MyFile *file = [[MyFile alloc] initWithFilePath:[documentsDirectoryURL path] mimeType:contentType];
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

参见 CocoaDocs 以获得 GTLRDataObject 参考。


通用版本:使用iOS SDK

如果您使用 NSURLSession,它有委托方法,您可以使用该方法将文件从临时位置移动到您需要的任何地方。

Obj-C

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // Use `location` to move your data to Documents directory or wherever else
}

Swift

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // Use `location` to move your data to Documents directory or wherever else
}