Search code examples
iosswiftswift3nsfilemanager

Swift how to create complex folder structure in temp folder


I would like to create folder structure in the temp folder of the application.

Structure of the folders should be:

  • iPhone

    • Intensity
      • Positive
      • Negative
    • Elipses
      • Positive
      • Negative
    • Composite
      • Positive
      • Negative

I am using FileManager to create directories.

class func createBaseDirectory() {

let filemgr = FileManager.default

let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)

let docsURL = dirPaths[0]

let newDir = docsURL.appendingPathComponent("iPhone").path

do {
    try filemgr.createDirectory(atPath: newDir, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    print("Error: \(error.localizedDescription)")
}
}

But this way is not efficient.Because i should duplicate quite a lot of code snippets. Do Swift language have some more convenient ways how to create folder structure ?


Solution

  • I created the following in a Swift playground (same as Martin R suggested), seems to work fine:

    import Foundation
    
    let fm = FileManager.default
    let baseUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    let subPaths = [
        "iPhone/Intensity/Positive",
        "iPhone/Intensity/Negative",
        "iPhone/Elipses/Positive",
        "iPhone/Elipses/Negative",
        "iPhone/Composite/Negative",
        "iPhone/Composite/Negative",
    ]
    
    subPaths.forEach { subPath in
        let url = baseUrl.appendingPathComponent(subPath)
        do {
            try fm.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
            print("path created: \(url)")
        } catch let error {
            print("error: \(error)")
        }
    }
    

    You could create an extension on NSFileManager using this code for reusability.