Is there a safer way to create a directory if it does not exist?
Swift 4.2
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let imagesPath = documentsURL.appendingPathComponent("Images")
do
{
try FileManager.default.createDirectory(atPath: imagesPath.path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
NSLog("Unable to create directory \(error.debugDescription)")
}
Swift 5.0
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let dataPath = docURL.appendingPathComponent("MyFolder")
if !FileManager.default.fileExists(atPath: dataPath.absoluteString) {
do {
try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription);
}
}
For Swift 3.0
do {
try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
You can actually skip the if
, even though Apple's docs say that the directory must not exist, that is only true if you are passing withIntermediateDirectories:NO
That puts it down to one call. The next step is to capture any errors:
NSError * error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:bundlePath
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (error != nil) {
NSLog(@"error creating directory: %@", error);
//..
}
This will not result in an error if the directory already exists.