获取临时目录中文件的路径和URL

58

我想获取名为"temp.pdf"的文件在NSTemporaryDirectory文件夹中的路径(我已经检查过,该文件存在)。

我使用以下代码:

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。

我如何访问文件路径?

3个回答

132

NSTemporaryDirectory()提供了一个完整的路径到临时目录。你是否尝试过使用它而不是使用mainBundle

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

如果你需要一个URL,可以这样做:

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

好的,当我这样做时,我想要使用filepath和[UIDocumentInteractionController interactionControllerWithURL:filepath]。我已经用[NSURL urlWithString:filepath]创建了它,但是Xcode显示:“无效的方案(null)。仅支持文件方案。” - HasgardLucian
19
尝试使用NSURL *furl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"]];这行代码。 - Joe
如果我们想返回临时目录中的所有PDF文件怎么办? - Eshwar Chaitanya

14

Swift 2.0

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

4

对于Swift 3.0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接