Skip to main content

Create NSURL for Temporary File

·1 min

I was recently working on some code that previews a PDF file. I had written a method to create the PDF that takes an NSURL object as an argument. I wanted to call that method to preview the PDF file, supplying an NSURL object for a temporary file. How do you create an NSURL object for a temporary file?

Call NSURL’s fileURLWithPath: method. To create the path for the URL, call the function NSTemporaryDirectory(), which returns the path to the user temporary directory. Then call NSString’s stringByAppendingPathComponent: method, supplying the name of the temporary file. The following code creates an NSURL object for a temporary file named TempPreview.pdf:

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