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

时间:2022-02-23 23:06:07

I try to get the file path of a file called "temp.pdf" wich is located in the NSTemporaryDirectory folder (I've checked, the file exists).

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

I use this :

我用这个:

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

I've tried with :

我试过了:

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

And :

和:

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

But it seems that it doesn't work, return value is always null.

但它似乎不管用,返回值总是空的。

So, i'm a little confused, someone can help me ?

我有点困惑,有人能帮我吗?

Thank you.

谢谢你!

3 个解决方案

#1


120  

NSTemporaryDirectory() provides a full path to the temporary directory. Instead of using your mainBundle have you tried

NSTemporaryDirectory()提供临时目录的完整路径。你没有使用你的主包,而是尝试了

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

If you need a URL instead, do this:

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

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

#2


13  

Swift 2.0

斯威夫特2.0

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

#3


0  

For Swift 3.0

斯威夫特3.0

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

#1


120  

NSTemporaryDirectory() provides a full path to the temporary directory. Instead of using your mainBundle have you tried

NSTemporaryDirectory()提供临时目录的完整路径。你没有使用你的主包,而是尝试了

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

If you need a URL instead, do this:

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

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

#2


13  

Swift 2.0

斯威夫特2.0

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

#3


0  

For Swift 3.0

斯威夫特3.0

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