gpt4 book ai didi

ios - 如何将 NSData 内容复制到临时文件?

转载 作者:行者123 更新时间:2023-12-01 15:58:55 25 4
gpt4 key购买 nike

我正在从 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/
看起来类引用可能会公开一个方法来做到这一点:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/
编辑
我的解决方案有效。最终成为我需要使用 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);
}

最佳答案

您可以直接将 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 方法将自动覆盖该文件。

关于ios - 如何将 NSData 内容复制到临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33727561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com