Is there a safer way to create a directory if it does not exist? Is there a safer way to create a directory if it does not exist? ios ios

Is there a safer way to create a directory if it does not exist?


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.


For Swift 3.0

do {    try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true, attributes: nil)} catch {    print(error)}


Swift 4.2

let fileManager = FileManager.defaultlet 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)")}