58

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
HasgardLucian
  • 613
  • 1
  • 5
  • 6

3 Answers3

132

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"]];
Alex Terente
  • 12,006
  • 5
  • 51
  • 71
Joe
  • 56,979
  • 9
  • 128
  • 135
  • OK, when I do that, I want to use filepath with [UIDocumentInteractionController interactionControllerWithURL:filepath]; I've made [NSURL urlWithString:filepath], but Xcode says : "Invalid scheme (null). Only the file scheme is supported." – HasgardLucian Aug 16 '11 at 13:30
  • 19
    Try `NSURL *furl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"]];` – Joe Aug 16 '11 at 13:38
  • What if we want to return all pdf files in temp directory?? – Eshwar Chaitanya Dec 22 '14 at 15:41
14

Swift 2.0

let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(),isDirectory: true)
let fileURL = tmpDirURL.URLByAppendingPathComponent("stuff").URLByAppendingPathExtension("gif")
print("FilePath: \(fileURL.path)")
twtr
  • 365
  • 1
  • 5
  • 15
4

For Swift 3.0

var fileUrl: URL = URL(fileURLWithPath: NSTemporaryDirectory())
fileUrl.appendPathComponent("foo")
fileUrl.appendPathExtension("bar")
bompf
  • 1,374
  • 1
  • 18
  • 24