Skip to content

Instantly share code, notes, and snippets.

@viccc
Last active January 22, 2016 17:00
Show Gist options
  • Save viccc/43e4872c1985ee8050c1 to your computer and use it in GitHub Desktop.
Save viccc/43e4872c1985ee8050c1 to your computer and use it in GitHub Desktop.
Utility functions to create a unique file name in a given directory, with shorter helper functions for Documents, ApplicationSupport, tmp, Caches
extension NSFileManager {
class func uniqueDocumentFileURLWithBaseName(baseName: String) throws -> NSURL {
let directoryUrl = try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
return try directoryUrl.URLByAppendingUniqueFileNameWithBaseName(baseName)
}
class func uniqueAppSupportFileURL(inSubdirectory subdirectory: String, uniqueFileBaseName baseName: String) throws -> NSURL {
let appSupportUrl = try NSFileManager.defaultManager().URLForDirectory(.ApplicationSupportDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let directoryUrl: NSURL
if subdirectory.isEmpty {
directoryUrl = appSupportUrl
} else {
directoryUrl = appSupportUrl.URLByAppendingPathComponent(subdirectory, isDirectory: true)
}
return try directoryUrl.URLByAppendingUniqueFileNameWithBaseName(baseName)
}
class func uniqueCacheFileURLWithBaseName(baseName: String) throws -> NSURL {
let directoryUrl = try NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
return try directoryUrl.URLByAppendingUniqueFileNameWithBaseName(baseName)
}
class func uniqueTemporaryFileNameWithBaseName(baseName: String) throws -> NSURL {
let tmpDir = NSURL(fileURLWithPath: NSTemporaryDirectory())
return try tmpDir.URLByAppendingUniqueFileNameWithBaseName(baseName)
}
}
extension NSURL {
func URLByAppendingUniqueFileNameWithBaseName(fileBaseName: String) throws -> NSURL {
let baseName: String
let fileExtension: String
do {
let ext = (fileBaseName as NSString).pathExtension
if !ext.isEmpty {
baseName = (fileBaseName as NSString).stringByDeletingPathExtension
fileExtension = ext
} else {
baseName = fileBaseName
fileExtension = ""
}
}
enum Error: ErrorType {
case NotADirectory
}
do {
try NSFileManager.defaultManager().createDirectoryAtURL(self, withIntermediateDirectories: true, attributes: nil)
} catch {
throw Error.NotADirectory
}
let directoryURL = self
var fileCount = 1;
while true {
let fileName = baseName + ((fileCount > 1) ? String(" (\(fileCount))") : "") + (fileExtension.isEmpty ? "" : String(".\(fileExtension)"))
let fileUrl = directoryURL.URLByAppendingPathComponent(fileName)
if !fileUrl.checkResourceIsReachableAndReturnError(nil) {
return fileUrl
}
fileCount++
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment