Home > DeveloperSection > Forums > How do we create a temporary file in iOS
Tarun Kumar

Total Post:214

Posted on    September-05-2015 12:25 AM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 940  View(s)
Rate this:

In C# we could easily create a temporary file and get its name using this function:



This function would create a file with a unique name in the temporary directory and return the full path to that file.

In the Cocoa API's, the closest thing we find is: NSTemporaryDirectory

We are missing something obvious or is there no built in way to do this?

Mikki Halpin
Mikki Halpin

Total Post:23

Posted on    September-07-2015 12:02 AM

I created a pure Cocoa solution by way of a category on NSFileManager that uses a combination of NSTemporary() and a globally unique ID. 

Here the header file: 

@interface NSFileManager (TemporaryDirectory)

    -(NSString *) createTemporaryDirectory; 



And the implementation file:

@implementation NSFileManager (TemporaryDirectory)

-(NSString *) createTemporaryDirectory {

    // Create a unique directory in the system temporary directory

    NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:guid];

    if (![self createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]) {

            return nil;


    return path;



This creates a temporary directory but could be easily adapted to use createFileAtPath:contents:attributes: instead of createDirectoryAtPath: to create a file instead.

Don't want to miss updates? Please click the below button!

Follow MindStick