Create Folder in Swift

后端 未结 3 482
生来不讨喜
生来不讨喜 2020-12-15 13:02

I\'m new to swift and I\'m not sure how to make a new folder from a string path (or from some kind of File/ NSFile object)

This is on OS X with Cocoa.

相关标签:
3条回答
  • 2020-12-15 13:28

    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)
    
    0 讨论(0)
  • 2020-12-15 13:43

    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

    0 讨论(0)
  • 2020-12-15 13:44

    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.")
    }
    
    0 讨论(0)
提交回复
热议问题