Search code examples
swiftmacoscocoapermissions

How to create a directory in downloads folder with Swift on macOS? Permission exception


I am struggling to simply create a folder in the users download directory on macOS with this code:

static func createFolderInDownloadsDirectory() {
    let downloadsDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first!
    let downloadsDirectoryWithFolder = downloadsDirectory.appendingPathComponent("FolderToCreate")
    
    do {
        try FileManager.default.createDirectory(at: downloadsDirectoryWithFolder, withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
}

This is the output:

You don’t have permission to save the file “FolderToCreate” in the folder “Downloads”. 

How can I fix this?


Solution

  • Xcode 9 and later enables sandboxing by default, which severely limits interactions with the system. However you can still write to the Downloads folder by adding an entitlement to your app:

    Select your target, then Capabilities and set Downloads Folder to Read/Write:

    Enable read/write to Downloads Folder under App Sandbox

    If you have no intention of distributing your app through the Mac App Store, you can turn off sandboxing. Your application can still be signed but users will get a warning when they first launch your app.