我正在从S3存储桶下载可能是大文件的内容,并希望将其保存在视图控制器之间,以便在短时间内使用。我喜欢tmp
目录,因为对文件大小的限制较少,而且似乎也没有理由将其保存在Documents目录中。
我可以使用:
构建tmp
的路径
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"image"] URLByAppendingPathExtension:@"png"];
NSLog(@"fileURL: %@", [fileURL path]);
但我不确定如何将已下载的NSData *
写入/覆盖到该路径。
我基本上只想用命令行更清楚地表达一下:
wget https://example.com/image.png
cp image.png /tmp/
看起来类引用可能会公开一个方法来执行此操作:
我的解决方案有效。结果是我需要使用writeToURL
。从这里得到的灵感:
http://nshipster.com/nstemporarydirectory/
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/clm/NSURL/fileURLWithPath:isDirectory:
#define S3_LATEST_IMAGE_FILEPATH @"test-image.png"
// Write the downloaded result to the filesystem
NSError *error;
NSString *fileName = [NSString stringWithFormat:@"%@_%@", [[NSProcessInfo processInfo] globallyUniqueString], S3_LATEST_IMAGE_FILEPATH];
NSURL *directoryURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]] isDirectory:YES];
[[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"Error1: %@", error);
return;
}
NSURL *fileURL = [directoryURL URLByAppendingPathComponent:fileName];
NSString *path = fileURL.absoluteString;
NSLog(@"fileURL.absoluteString: %@", path);
[data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (error) {
NSLog(@"Error: %@", error);
}
答案 0 :(得分:3)
您可以通过
直接将NSData写入路径NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"newest-fw"] URLByAppendingPathExtension:@"zip"];
NSString *path= fileURL.absoluteString;
//data would be the NSData that you get from the S3 bucket
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtURL: fileURL withIntermediateDirectories:NO attributes:nil error:&error];
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSData的writeToFile方法会自动覆盖以前存在的文件。