如何在MacOS上使用Swift快速在Downloads文件夹中创建目录?权限异常. [英] How to create a directory in downloads folder with swift on macos? Permission exception.

查看:159
本文介绍了如何在MacOS上使用Swift快速在Downloads文件夹中创建目录?权限异常.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是输出:

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

我该如何解决?

推荐答案

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

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:

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

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.

这篇关于如何在MacOS上使用Swift快速在Downloads文件夹中创建目录?权限异常.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆