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

时间:2015-11-16 02:16:55

标签: ios objective-c amazon-s3

我正在从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/

看起来类引用可能会公开一个方法来执行此操作:

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

1 个答案:

答案 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方法会自动覆盖以前存在的文件。