【问题标题】:How can I save an image to my app's tmp dir?如何将图像保存到我的应用程序的 tmp 目录?
【发布时间】:2011-09-16 12:55:52
【问题描述】:

为什么如果我使用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];
}

【问题讨论】:

  • 本帖讲解iOS应用的所有目录,保存,删除kmithi.blogspot.in/2012/08/…
  • UIImageJPEGRepresentation() 已经返回NSData * - 为什么在使用之前将它传递给dataWithData:?我想知道你是否知道一些我不知道的事情......

标签: iphone xcode tmp


【解决方案1】:

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

斯威夫特 4.1

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

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

斯威夫特 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/

保证保留旧版本(不包括&lt;Application_Home&gt;/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"];

【讨论】:

  • 当视频文件为 .mp4 时,我无法从 NSTemporaryDirectory () 获取文件。非常适合音频和图像。帮助
  • @jose920405 我不太明白你的问题,但可能与iOS是否支持该文件有关。
  • isDirectory 很重要
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    Swift 5 版本的Sverrisson 的回答。

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

    【讨论】:

      【解决方案4】:

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

      然后使用 nshomedirectory() 为您提供位置到 /Users/MyMac/Library/Application Support/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"];
      

      【讨论】:

      • 这不起作用,文本谈到 NSHomeDirectory() 并且代码使用 NSDocumentDirectory 因此,/tmp 目录将成为 Documents 目录的一部分,这是错误的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2012-08-13
      • 1970-01-01
      相关资源
      最近更新 更多