Create folder in Swift
3 answers
I understand that you are trying to create a directory programmatically using swift. The code below does the same.
var err: NSErrorPointer = nil
let manager = NSFileManager.defaultManager()
manager.createDirectoryAtPath("/Users/abc/Desktop/swiftDir", withIntermediateDirectories: true, attributes: nil, error: err)
+8
source to share
Xcode 8 β’ Swift 3
extension FileManager.SearchPathDirectory {
func createSubFolder(named: String, withIntermediateDirectories: Bool = false) -> Bool {
guard let url = FileManager.default.urls(for: self, in: .userDomainMask).first else { return false }
do {
try FileManager.default.createDirectory(at: url.appendingPathComponent(named), withIntermediateDirectories: withIntermediateDirectories, attributes: nil)
return true
} catch {
print(error)
return false
}
}
}
Using:
if FileManager.SearchPathDirectory.desktopDirectory.createSubFolder(named: "untitled folder") {
print("folder successfully created")
}
+5
source to share
In Swift 2.0, you have to use the new style for error handling:
let path: String = "/Users/abc/Desktop/swiftDir"
let fileManager = NSFileManager.defaultManager()
do
{
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
print("Error while creating a folder.")
}
+3
source to share