tmlen tmlen - 2 months ago 27
Swift Question

Temporary file path using swift

How to get a unique temporary file path using Swift/Cocoa on OS X?
Cocoa does not seem to provide a function for this, only

NSTemporaryDirectory()
which returns the path of the temporary directory. Using the BSD
mktemp
function requires a mutable C-string as argument.

Answer

Here is a possible method to use mkstemp() from Swift. NSURL methods are used to convert between NSURL and C strings representing the file system path:

// The template string:
let template = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("file.XXXXXX")

// Fill buffer with a C string representing the local file system path. 
var buffer = [Int8](count: Int(PATH_MAX), repeatedValue: 0)
template.getFileSystemRepresentation(&buffer, maxLength: buffer.count)

// Create unique file name (and open file):
let fd = mkstemp(&buffer)
if fd != -1 {

    // Create URL from file system string:
    let url = NSURL(fileURLWithFileSystemRepresentation: buffer, isDirectory: false, relativeToURL: nil)
    print(url.path!)

} else {
    print("Error: " + String(strerror(errno)))
}