【问题标题】:Get file path and URL for file in temp directory获取临时目录中文件的文件路径和 URL
【发布时间】:2011-10-28 01:45:29
【问题描述】:

我正在尝试获取位于 NSTemporaryDirectory 文件夹中的名为“temp.pdf”的文件的文件路径(我已检查,该文件存在)。

我用这个:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"temp" ofType:@"pdf" inDirectory:NSTemporaryDirectory()];

我试过了:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"temp.pdf" ofType:@"" inDirectory:NSTemporaryDirectory()];

还有:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"temp" ofType:@"pdf"];

但是好像不行,返回值总是null。

如何访问文件路径?

【问题讨论】:

    标签: objective-c ios cocoa nsbundle


    【解决方案1】:

    NSTemporaryDirectory() 提供临时目录的完整路径。而不是使用你的mainBundle 你试过了吗

    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"];
    

    如果您需要 URL,请执行以下操作:

    NSURL *furl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"]];
    

    【讨论】:

    • 好的,当我这样做时,我想将文件路径与 [UIDocumentInteractionController interactionControllerWithURL:filepath] 一起使用;我已经制作了 [NSURL urlWithString:filepath],但 Xcode 说:“无效方案(空)。仅支持文件方案。”
    • 试试NSURL *furl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"]];
    • 如果我们想返回temp目录下的所有pdf文件怎么办??
    【解决方案2】:

    Swift 2.0

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

    【讨论】:

      【解决方案3】:

      对于 Swift 3.0

      var fileUrl: URL = URL(fileURLWithPath: NSTemporaryDirectory())
      fileUrl.appendPathComponent("foo")
      fileUrl.appendPathExtension("bar")
      

      【讨论】:

        猜你喜欢
        • 2012-08-19
        • 2013-10-08
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 2015-10-29
        • 2014-04-21
        • 2015-12-07
        • 2023-04-05
        相关资源
        最近更新 更多