作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在从 S3 存储桶下载可能是大文件的文件,并希望将其保存在 View Controller 之间以便稍后使用。我喜欢 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
.灵感来自这里:
#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);
}
最佳答案
您可以直接将 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];
关于ios - 如何将 NSData 内容复制到临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33727561/
我是一名优秀的程序员,十分优秀!