Get file path and URL for file in temp directory

Objective CIosCocoaNsbundle

Objective C Problem Overview


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

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.

How can I access the file path?

Objective C Solutions


Solution 1 - Objective C

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

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

If you need a URL instead, do this:

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

Solution 2 - Objective C

Swift 2.0

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

Solution 3 - Objective C

For Swift 3.0

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHasgardLucianView Question on Stackoverflow
Solution 1 - Objective CJoeView Answer on Stackoverflow
Solution 2 - Objective CtwtrView Answer on Stackoverflow
Solution 3 - Objective CbompfView Answer on Stackoverflow