Volumes have been written about persisting data, but when it comes to short-lived, temporary files, there is very little to go on for Cocoa. (Or if there has, perhaps it was poetically ephemeral itself).
Temporary files are used to write data to disk
before either moving it to a permanent location
or discarding it.
For example, when a movie editor app exports a project,
it may write each frame to a temporary file until it reaches the end
and moves the completed file to the ~/Movies
directory.
Using a temporary file for these kinds of situations
ensures that tasks are completed atomically
(either you get a finished product or nothing at all; nothing half-way),
and without creating excessive memory pressure on the system
(on most computers, disk space is plentiful whereas memory is limited).
There are four distinct steps to working with a temporary file:
- Creating a temporary directory in the filesystem
- Creating a temporary file in that directory with a unique filename
- Writing data to the temporary file
- Moving or deleting the temporary file once you’re finished with it
Creating a Temporary Directory
The first step to creating a temporary file is to find a reasonable, out-of-the-way location to which you can write — somewhere inconspicuous that get in the way of the user or accidentally get picked up by a system process like Spotlight indexing, Time Machine backups, or iCloud sync.
On Unix systems, the /tmp
directory is the de facto scratch space.
However, today’s macOS and iOS apps run in a container
and don’t have access to system directories;
a hard-coded path like that isn’t going to cut it.
Instead, let’s ask File
to point us in the right direction
using the uri(for:in:appropriate
method:
lettemporaryDirectoryURL=tryFileManager.default.url(for:.itemReplacementDirectory,in:.userDomainMask,appropriateFor:URL(fileURLWithPath:"/"),create:true)
NSFileManager*fileManager=[NSFileManagerdefaultManager];NSError*error=nil;NSURL*temporaryDirectoryURL=[fileManagerURLForDirectory:NSItemReplacementDirectoryinDomain:NSUserDomainMaskappropriateForURL:[NSURLfileURLWithPath:@"/"]create:YESerror:&error];
The parameters of this method are frequently misunderstood, so let’s go through each to understand what this method actually does:
- We pass the item replacement search path (
.item
) to say that we’re interested in a temporary directory.Replacement Directory - We pass the user domain mask (
.user
) to get a directory that’s accessible to the user.Domain Mask - For the
appropriate
parameter, the only part of the file URL that’s considered is the volume; therefore, we can passFor URL URL(file
to specify the current volume.URLWith Path: "/") - Finally, we pass
true
to thecreate
parameter to save us the additional step of creating it ourselves.
The resulting directory will have a path that looks something like this: file:///var/folders/l3/kyksr35977d8nfl1mhw6l_c00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20NSHipster%208)/
Creating a Temporary File
With a place to call home (at least temporarily), the next step is to figure out what to call our temporary file. We’re not picky about what to it’s named — just so long as it’s unique, and doesn’t interfere with any other temporary files in the directory.
The best way to generate a unique identifier
is the Process
property globally
:
ProcessInfo().globallyUniqueString
[[NSProcessInfoprocessInfo]globallyUniqueString];
The resulting filename will look something like this: 42BC63F7-E79E-4E41-8E0D-B72B049E9254-25121-000144AB9F08C9C1
Alternatively,
UUID
also produces workably unique identifiers:
UUID().uuidString
[[NSUUIDUUID]UUIDString]
A generated UUID string has the following format: B49C292E-573D-4F5B-A362-3F2291A786E7
Now that we have an appropriate directory and a unique filename, let’s put them together to create our temporary file:
lettemporaryDirectoryURL=tryFileManager.default.url(for:.itemReplacementDirectory,in:.userDomainMask,appropriateFor:URL(fileURLWithPath:"/"),create:true)lettemporaryFilename=ProcessInfo().globallyUniqueStringlettemporaryFileURL=temporaryDirectoryURL.appendingPathComponent(temporaryFilename)
NSFileManager*fileManager=[NSFileManagerdefaultManager];NSError*error=nil;NSURL*temporaryDirectoryURL=[fileManagerURLForDirectory:NSItemReplacementDirectoryinDomain:NSUserDomainMaskappropriateForURL:[NSURLfileURLWithPath:@"/"]create:YESerror:&error];NSString*temporaryFilename=[[NSProcessInfoprocessInfo]globallyUniqueString];NSURL*temporaryFileURL=[temporaryDirectoryURLURLByAppendingPathComponent:temporaryFilename];
Writing to a Temporary File
The sole act of creating a file URL is of no consequence to the file system; a file is created only when the file path is written to. So let’s talk about our options for doing that:
Writing Data to a URL
The simplest way to write data to a file
is to call the Data
method write(to:options)
:
letdata:Datatrydata.write(to:temporaryFileURL,options:.atomicWrite)
NSData*data;NSError*error=nil;[datawriteToURL:temporaryFileURLoptions:NSDataWritingAtomicerror:&error];
By passing the atomic
option,
we ensure that either all of the data is written
or the method returns an error.
Writing Data to a File Handle
If you’re doing anything more complicated
than writing a single Data
object to a file,
consider creating a File
instead, like so:
letfileHandle=tryFileHandle(forWritingTo:temporaryFileURL)defer{fileHandle.closeFile()}fileHandle.write(data)
NSError*error=nil;NSFileHandle*fileHandle=[NSFileHandlefileHandleForWritingToURL:temporaryFileURLerror:&error];[fileHandlewriteData:data];[fileHandlecloseFile];
Writing Data to an Output Stream
For more advanced APIs,
it’s not uncommon to use Output
to direct the flow of data.
Creating an output stream to a temporary file
is no different than any other kind of file:
letoutputStream=OutputStream(url:temporaryFileURL,append:true)!defer{outputStream.close()}data.withUnsafeBytes{bytesinoutputStream.write(bytes,maxLength:bytes.count)}
NSOutputStream*outputStream=[NSOutputStreamoutputStreamWithURL:temporaryFileURLappend:YES];[outputStreamwrite:data.bytesmaxLength:data.length];[outputStreamclose];
Moving or Deleting the Temporary File
Files in system-designated temporary directories are periodically deleted by the operating system. So if you intend to hold onto the file that you’ve been writing to, you need to move it somewhere outside the line of fire.
If you already know where the file’s going to live,
you can use File
to move it to its permanent home:
letfileURL:URLtryFileManager.default.moveItem(at:temporaryFileURL,to:fileURL)
NSFileManager*fileManager=[NSFileManagerdefaultManager];NSURL*fileURL;NSError*error=nil;[fileManagermoveItemAtURL:temporaryFileURLtoURL:fileURLerror:&error];
Although the system eventually takes care of files in temporary directories, it’s not a bad idea to be a responsible citizen and follow the guidance of “take only pictures; leave only footprints.”
File
can help us out here as well,
with the remove
method:
tryFileManager.default.removeItem(at:temporaryFileURL)
NSFileManager*fileManager=[NSFileManagerdefaultManager];NSError*error=nil;[fileManagerremoveItemAtURL:temporaryFileURLerror:&error];
“This too shall pass” is a mantra that acknowledges that all things are indeed temporary.
Within the context of the application lifecycle, some things are more temporary than others, and it’s with that knowledge that we choose to act appropriately: seeking to find the right place, make a unique impact, and leave without a trace.
Perhaps we can learn something from this cycle in our own, brief and glorious lifecycle.