HOW DO WE CREATE A TEMPORARY FILE IN IOS

Tarun Kumar

Total Post:214

Points:1642
Posted by  Tarun Kumar
 1008  View(s)
Ratings:
Rate this:

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

Path.GetTempFileName();

 

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?

  1. Mikki Halpin

    Post:23

    Points:161
    Re: How do we create a temporary file in iOS

    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; 

    @end

     

    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;

    } 

    @end

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!