How to create directory using Swift code (NSFileManager)

63,298

Solution 1

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.path) {
    do {
        try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
    } catch {
        print(error.localizedDescription)
    }
}

Swift 4.0

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0] as AnyObject
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!
    
do {
    try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription)
}

Swift 3.0

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!
        
do {
    try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription)
}

Swift 2.1

You can create directory using below method:

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")

do {
    try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription)
}

Solution 2

None of @Kampai and @Crashalot's answers worked for me.

The .absoluteString makes a url with file:// prefix and it cause exception while creating directory. Instead I've used .path method.

The fixed code for Swift 3

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")

do {
    try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    print("Error creating directory: \(error.localizedDescription)")
}

Solution 3

The accepted answer no longer compiles as the line with appendingPathComponent generates an error.

Here's a Swift 3 version that compiles:

fileprivate func createDir(dirName: String) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let dataPath = documentsDirectory.appendingPathComponent(dirName)

    do {
        try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
    } catch let error as NSError {
        printError("Error creating directory: \(error.localizedDescription)")
    }
}

Solution 4

Swift 4 :

NSSearchPathForDirectoriesInDomains returns an array of strings, not URLs.

appendingPathComponent to string makes app crash with the message -[NSPathStore2 URLByAppendingPathComponent:]: unrecognized selector sent to instance

Here's a Swift 4 version that compiles:

    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    if let pathURL = URL.init(string: paths[0]) {
        let dataURL = pathURL.appendingPathComponent("MyFolder")
        do {
            try FileManager.default.createDirectory(atPath: dataURL.absoluteString, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription);
        }
    }
    else {
        print("Error in getting path URL");
    }

Solution 5

Simpler solution:

"~/Desktop/demo".expand.createDir()//Now you have a folder named demo on your desk

extension String{
    func createDir(_ path:String){
        do {
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }
    }
    var expand:String {return NSString(string: self).expandingTildeInPath}
}
Share:
63,298
Gian
Author by

Gian

Updated on April 14, 2021

Comments

  • Gian
    Gian about 3 years

    I'm having some trouble with converting Objective-C code to create a directory for Swift.

    Objective-C:

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];
    
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
    
  • Siamaster
    Siamaster over 8 years
    As of Swift 2: do { try fileManager.createDirectoryAtPath(outputPath, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription); }
  • Jack
    Jack about 7 years
    Kudos to you, I've been trying to figure this out for a day!
  • thacilima
    thacilima almost 7 years
    Thanks, .path was the missing part for me
  • Suhail Parvez
    Suhail Parvez over 6 years
    I did try this on an iPhone but i could not find the created folder in the device. Have updated the device to iOS 11, which has the files App.
  • Arpit B Parekh
    Arpit B Parekh about 6 years
    While creaing folder, do we neeeed to check, whether folder exists or not ?
  • Mehdi Hosseinzadeh
    Mehdi Hosseinzadeh about 6 years
    No, It's not needed because we send withIntermediateDirectories: true. If folder created/exists it will return true anyway. You can read more here: developer.apple.com/documentation/foundation/filemanager/…
  • Dani
    Dani over 4 years
    "myfolder"? Do you mean "myfile"?
  • Dani
    Dani over 4 years
    I get an error that I don't have persmission to access the file after creating it with this code
  • Kampai
    Kampai over 4 years
    @DanielSpringer: Please read the question, the answer is about to create a directory using Swift. So this code will not work for you, as you are trying to create file using createDirectory() function.
  • Dani
    Dani over 4 years
    @Kampai yes I see that this answer is to the question. I had a similar/related question.
  • Kampai
    Kampai over 4 years
    @DanielSpringer: Please let me know your queries, I am here to help you.
  • Dani
    Dani over 4 years
    @Kampai I’m trying to read the created file using above code but get “permission denied” error. How do I create a file, so that attempting to write to it doesn’t give “no such file” error?
  • Kampai
    Kampai over 4 years
    @DanielSpringer: Can you please provide, Xcode version and iOS version?
  • SafeFastExpressive
    SafeFastExpressive over 3 years
    @Kampai Upvoted just because you implemented error checking/reporting. Kudos!
  • Bogdan Razvan
    Bogdan Razvan over 3 years
    Use relativePath instead of absoluteString
  • Sergey
    Sergey about 3 years
    Just path instead of absoluteString.
  • johnrubythecat
    johnrubythecat about 3 years
    let docURL = URL(fileURLWithPath: documentsDirectory) if you want to append a file into the path. replace 'string' with 'fileURLWithPath' or you get a URL scheme error. Otherwise, nice code, thank you.