如何将图像保存到应用程序的临时目录?

发布于 2024-12-05 03:01:36 字数 1159 浏览 2 评论 0原文

为什么如果我使用 NSTemporaryDirectory 保存图像,图像会保存到

/var/folders/oG/oGrLHcAUEQubd3CBTs-1zU+++TI/-Tmp-/

而不是进入

/Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF/tmp

这是我的代码:

-(NSString *)tempPath
{
    return NSTemporaryDirectory();
}

-(void) saveMyFoto
{
    NSString *urlNahledu = [NSString stringWithFormat:@"%@%@%@",@"http://www.czechmat.cz", urlFotky,@"_100x100.jpg"];
    NSLog(@"%@", urlNahledu);


    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlNahledu]]];

    NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.8f)];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSLog(@"%@    %@", paths, [self tempPath]);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"];

    [data writeToFile:localFilePath atomically:YES];
}

Why is that if I use NSTemporaryDirectory to save my image, the image is saved into

/var/folders/oG/oGrLHcAUEQubd3CBTs-1zU+++TI/-Tmp-/

and not into

/Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF/tmp

Here is my code:

-(NSString *)tempPath
{
    return NSTemporaryDirectory();
}

-(void) saveMyFoto
{
    NSString *urlNahledu = [NSString stringWithFormat:@"%@%@%@",@"http://www.czechmat.cz", urlFotky,@"_100x100.jpg"];
    NSLog(@"%@", urlNahledu);


    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlNahledu]]];

    NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.8f)];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSLog(@"%@    %@", paths, [self tempPath]);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"];

    [data writeToFile:localFilePath atomically:YES];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黯然#的苍凉 2024-12-12 03:01:36

这是首选方法,它使用 URL 直接获取 tmp 目录的链接,然后返回该目录的文件 URL (pkm.jpg):

Swift 5+

let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    .appendingPathComponent("pkm", isDirectory: false)
    .appendingPathExtension("jpg")

// Then write to disk, here 0.8 is chosen for the compression quality
if let data = image.jpegData(compressionQuality: 0.8) {
    do {
        try data.write(to: url)
    } catch {
        print("Handle the error, i.e. disk can be full")
    }
}

Swift 4.1

let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    .appendingPathComponent("pkm", isDirectory: false)
    .appendingPathExtension("jpg")

// Then write to disk, here 0.8 is chosen for the quality
if let data = UIImageJPEGRepresentation(image, 0.8) {
    do {
        try data.write(to: url)
    } catch {
        print("Handle the error, i.e. disk can be full")
    }
}

Swift 3.1

let tmpURL = try! URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
                    .appendingPathComponent("pkm")
                    .appendingPathExtension("jpg")
print("Filepath: \(tmpURL)")

请注意,可能的错误不会被处理!

Swift 2.0

let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let fileURL = tmpDirURL.URLByAppendingPathComponent("pkm").URLByAppendingPathExtension("jpg")
print("FilePath: \(fileURL.path)")

Objective-C

NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"pkm"] URLByAppendingPathExtension:@"jpg"];
NSLog(@"fileURL: %@", [fileURL path]);

请注意,某些方法仍然请求字符串形式的路径,然后使用 [fileURL path] 以字符串形式返回路径(如上面 NSLog 中所示)。
升级当前应用程序时,

<Application_Home>/Documents/
<Application_Home>/Library/

保证保留旧版本文件夹中的所有文件(不包括 /Library/Caches 子目录)。使用 Documents 文件夹存放您可能希望用户有权访问的文件,使用 Library 文件夹存放应用程序使用但用户不应看到的文件。


另一种更长的方法可能是获取 tmp 目录的 url,首先获取 Document 目录并删除最后一个路径组件,然后添加 tmp 文件夹:

NSURL *documentDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSURL *tmpDir = [[documentDir URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"tmp" isDirectory:YES];
NSLog(@"tmpDir: %@", [tmpDir path]);

然后我们可以在那里寻址一个文件,即 pkm .jpg 如下所示:

NSString *fileName = @"pkm";
NSURL *fileURL = [tmpDir URLByAppendingPathComponent:fileName isDirectory:NO];
fileURL = [fileURL URLByAppendingPathExtension:@"jpg"];

使用字符串也可以完成同样的操作,这在较旧的 iOS 系统上使用过,但现在推荐使用上面的第一种 URL 方法(除非您正在写入较旧的系统:iPhone OS 2 或 3) ):

NSString *tmpDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
tmpDir = [[tmpDir stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"tmp"];
NSString *filePath = [[tmpDir stringByAppendingPathComponent:@"pkm"] stringByAppendingPathExtension:@"jpg"];

This is the preferred method which uses URL's to get a link directly to the tmp directory and then returns a file URL (pkm.jpg) for that directory:

Swift 5+

let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    .appendingPathComponent("pkm", isDirectory: false)
    .appendingPathExtension("jpg")

// Then write to disk, here 0.8 is chosen for the compression quality
if let data = image.jpegData(compressionQuality: 0.8) {
    do {
        try data.write(to: url)
    } catch {
        print("Handle the error, i.e. disk can be full")
    }
}

Swift 4.1

let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    .appendingPathComponent("pkm", isDirectory: false)
    .appendingPathExtension("jpg")

// Then write to disk, here 0.8 is chosen for the quality
if let data = UIImageJPEGRepresentation(image, 0.8) {
    do {
        try data.write(to: url)
    } catch {
        print("Handle the error, i.e. disk can be full")
    }
}

Swift 3.1

let tmpURL = try! URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
                    .appendingPathComponent("pkm")
                    .appendingPathExtension("jpg")
print("Filepath: \(tmpURL)")

Note that a possible error is not handled!

Swift 2.0

let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let fileURL = tmpDirURL.URLByAppendingPathComponent("pkm").URLByAppendingPathExtension("jpg")
print("FilePath: \(fileURL.path)")

Objective-C

NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"pkm"] URLByAppendingPathExtension:@"jpg"];
NSLog(@"fileURL: %@", [fileURL path]);

Note that some methods still request a path as string, then use the [fileURL path] to return the path as string (as shown above in the NSLog).
When upgrading a current App all files in the folders:

<Application_Home>/Documents/
<Application_Home>/Library/

are guaranteed to be preserved from the old version (excluding the <Application_Home>/Library/Caches subdirectory). Use the Documents folder for files you may want the user to have access to and the Library folder for files that the App uses and the User should not see.


Another longer way might be to get an url to the tmp directory, by first getting the Document directory and stripping the last path component and then adding the tmp folder:

NSURL *documentDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSURL *tmpDir = [[documentDir URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"tmp" isDirectory:YES];
NSLog(@"tmpDir: %@", [tmpDir path]);

Then we can address a file there, i.e. pkm.jpg as shown here:

NSString *fileName = @"pkm";
NSURL *fileURL = [tmpDir URLByAppendingPathComponent:fileName isDirectory:NO];
fileURL = [fileURL URLByAppendingPathExtension:@"jpg"];

The same may be accomplished with strings, which was used by the way on older iOS systems, but the first URL method above is the recommended one now (unless you are writing to older systems: iPhone OS 2 or 3):

NSString *tmpDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
tmpDir = [[tmpDir stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"tmp"];
NSString *filePath = [[tmpDir stringByAppendingPathComponent:@"pkm"] stringByAppendingPathExtension:@"jpg"];
烂柯人 2024-12-12 03:01:36

因为在模拟器中运行的应用程序并不像 iOS 设备中那样真正沙箱化。在模拟器上,Mac OS 的临时目录在 NSTemporaryDirectory() 中返回 - 在 iOS 设备上,临时目录实际上位于沙箱内。
作为应用程序开发人员,您不应担心这种差异。

Because apps running in the simulator are not really sandboxed like in iOS devices. On the simulator a temporary directory from Mac OS is returned in NSTemporaryDirectory() - on an iOS device the temporary directory is really within the sandbox.
That difference shouldn't concern you as an app developer.

回心转意 2024-12-12 03:01:36

Sverrisson 答案的 Swift 5 版本。

    let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
        .appendingPathComponent("pkm", isDirectory: false)
        .appendingPathExtension("jpg")
    
    // Then write to disk
    if let data = image.jpegData(compressionQuality: 0.8) {
        do {
            try data.write(to: url)
        } catch {
            print("Handle the error, i.e. disk can be full")
        }
    }

Swift 5 version of Sverrisson 's answer.

    let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
        .appendingPathComponent("pkm", isDirectory: false)
        .appendingPathExtension("jpg")
    
    // Then write to disk
    if let data = image.jpegData(compressionQuality: 0.8) {
        do {
            try data.write(to: url)
        } catch {
            print("Handle the error, i.e. disk can be full")
        }
    }
滥情空心 2024-12-12 03:01:36

如果您想将图像存储在 /Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF/tmp 中,

请使用 nshomedirectory() 为您提供到 /Users 的位置/MyMac/库/应用程序支持/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF 然后你只需放入 /tmp 并存储你的图像。

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                     NSUserDomainMask, YES); 
NSString* docDir = [paths objectAtIndex:0];
NSString* file = [docDir stringByAppendingString:@"/tmp"];

If you want to store your images in /Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF/tmp

then use nshomedirectory() which give you location upto /Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF then you just put /tmp and store your images.

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                     NSUserDomainMask, YES); 
NSString* docDir = [paths objectAtIndex:0];
NSString* file = [docDir stringByAppendingString:@"/tmp"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文