Is there a more simple way to create a directory in swift 5?

let applicationSupport = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)[0])

    let launcherdir = applicationSupport.appendingPathComponent("MyApp")
do {
    try FileManager.default.createDirectory(atPath: launcherdir!.path, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    print(error)
                }
Answered by DTS Engineer in 712125022

Your snippet is complicate by you mixing NSURL, URL, and file paths. My advice is that you work entirely in ‘URL space’, resulting in this code:

let fm = FileManager.default
let appSupport = try fm.url(for: .applicationDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let dir = appSupport.appendingPathComponent("MyApp", isDirectory: true)
try fm.createDirectory(at: dir, withIntermediateDirectories: true)

Note that by passing true to the withIntermediateDirectories parameter you won’t fail if the directory exists. If you want to fail if the directory exists, pass false there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The actual method that I use

Accepted Answer

Your snippet is complicate by you mixing NSURL, URL, and file paths. My advice is that you work entirely in ‘URL space’, resulting in this code:

let fm = FileManager.default
let appSupport = try fm.url(for: .applicationDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let dir = appSupport.appendingPathComponent("MyApp", isDirectory: true)
try fm.createDirectory(at: dir, withIntermediateDirectories: true)

Note that by passing true to the withIntermediateDirectories parameter you won’t fail if the directory exists. If you want to fail if the directory exists, pass false there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks very much

Is there a more simple way to create a directory in swift 5?
 
 
Q