Create Folder in Swift

My understanding is that you are trying to create a directory programmatically using swift. The code given below does the same.

    var err: NSErrorPointer = nil
    let manager = NSFileManager.defaultManager()
    manager.createDirectoryAtPath("/Users/abc/Desktop/swiftDir", withIntermediateDirectories: true, attributes: nil, error: err)

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
        }
    }
}

Usage:

if FileManager.SearchPathDirectory.desktopDirectory.createSubFolder(named: "untitled folder") {
    print("folder successfully created")
}

SearchPathDirectory


In Swift 2.0 you must 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.")
}

Tags:

Macos

Swift