Skip to content

Instantly share code, notes, and snippets.

@russbishop
Last active February 8, 2016 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russbishop/e4cbc3d498b22f335b8a to your computer and use it in GitHub Desktop.
Save russbishop/e4cbc3d498b22f335b8a to your computer and use it in GitHub Desktop.
// Working around Foundation deficiencies when trying to append to a file
// (and without run loops, delegates, and other BS).
// Why is this so complicated?
import Foundation
public final class TemporaryFile {
public let handle: NSFileHandle //IUO until Swift 2.2
public let url: NSURL
/// Creates a temporary file with a random name in the given directory
public init(inDirectory: NSURL) throws {
self.url = inDirectory.URLByAppendingPathComponent(NSUUID().UUIDString)
let data = NSData()
do {
try data.writeToURL(self.url, options: NSDataWritingOptions())
self.handle = try NSFileHandle(forWritingToURL: self.url)
} catch {
self.handle = NSFileHandle()
throw error
}
}
/// Creates a temporary file with a random name in the temporary files directory
public convenience init() throws {
try self.init(inDirectory: NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true))
}
public func write(data: NSData) {
self.handle.writeData(data)
}
public func write(buffer: [UInt8]) {
buffer.withUnsafeBufferPointer { (ptr) -> Void in
let data = NSData(bytes: UnsafePointer<Void>(ptr.baseAddress), length: ptr.count)
self.write(data)
}
}
public func moveTo(destination: NSURL) throws {
try NSFileManager.defaultManager().moveItemAtURL(self.url, toURL: destination)
}
/// Returns a memory-mapped `NSData` of the file contents. Used for testing.
public func read() throws -> NSData {
return try NSData(contentsOfURL: self.url, options: NSDataReadingOptions.DataReadingMappedIfSafe)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment