如何在 macOS 上使用 swift 在 downloads 文件夹中创建目录?权限异常。

问题描述 投票:0回答:2

我正在努力使用以下代码在 macos 上的用户下载目录中创建一个文件夹:

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

这是输出:

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

我该如何解决这个问题?

swift macos cocoa permissions
2个回答
13
投票

Xcode 9 及更高版本默认启用沙箱,这严重限制了与系统的交互。但是,您仍然可以通过向应用程序添加权利来写入“下载”文件夹:

选择您的目标,然后功能并将下载文件夹设置为读/写:

如果您不打算通过 Mac App Store 分发您的应用程序,您可以关闭沙箱。您的应用程序仍然可以签名,但用户首次启动您的应用程序时会收到警告。


0
投票

Xcode 版本 15.2 (15C500b)

在目标->您的项目->签名和功能->应用程序沙箱中设置应用程序沙箱

© www.soinside.com 2019 - 2024. All rights reserved.