How to create directory using Swift code (NSFileManager)
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}
}
Gian
Updated on April 14, 2021Comments
-
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 over 8 yearsAs of Swift 2: do { try fileManager.createDirectoryAtPath(outputPath, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription); }
-
Jack about 7 yearsKudos to you, I've been trying to figure this out for a day!
-
thacilima almost 7 yearsThanks, .path was the missing part for me
-
Suhail Parvez over 6 yearsI 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 about 6 yearsWhile creaing folder, do we neeeed to check, whether folder exists or not ?
-
Mehdi Hosseinzadeh about 6 yearsNo, 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 over 4 years"myfolder"? Do you mean "myfile"?
-
Dani over 4 yearsI get an error that I don't have persmission to access the file after creating it with this code
-
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 over 4 years@Kampai yes I see that this answer is to the question. I had a similar/related question.
-
Kampai over 4 years@DanielSpringer: Please let me know your queries, I am here to help you.
-
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 over 4 years@DanielSpringer: Can you please provide, Xcode version and iOS version?
-
SafeFastExpressive over 3 years@Kampai Upvoted just because you implemented error checking/reporting. Kudos!
-
Bogdan Razvan over 3 yearsUse relativePath instead of absoluteString
-
Sergey about 3 yearsJust path instead of absoluteString.
-
johnrubythecat about 3 yearslet 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.