首页 > 解决方案 > macOS Swift-App 写权限问题?

问题描述

首先我要说:

问题是,我尝试通过 FileManager.default.createFile 在 /Library/Application 支持中创建一个文件,该文件在我的主文件夹中有效,例如 /Users/username/Library,所以它不应该是一个编程问题。

但我似乎没有写入 /Library 的权限...如何授予我的应用程序这些权限?

感谢所有帮助。

谢谢!

标签: swiftmacosfilepermissionsmacos-mojave

解决方案


您可以尝试打开 NSOpenPanel 并明确获取该文件夹的权限。这是一些帮助您入门的代码。

public static func allow(folder: String, prompt: String, callback: @escaping (URL?) -> ())
{
    let openPanel = NSOpenPanel()
    openPanel.directoryURL = URL(string: folder)
    openPanel.allowsMultipleSelection = false
    openPanel.canChooseDirectories = true
    openPanel.canCreateDirectories = false
    openPanel.canChooseFiles = false
    openPanel.prompt = prompt

    openPanel.beginSheetModal(for: self.window!) // use the window from your ViewController
    {
        result in
        if result.rawValue == NSFileHandlingPanelOKButton
        {
            if let url = openPanel.url
            {
                self.store(url: url) // Store for later use.
            }
        }
    }
}

public static func store(url: URL)
{
    guard let path = self.path else { return }

    do
    {
        let data = try url.bookmarkData(options: NSURL.BookmarkCreationOptions.withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)

        NSKeyedArchiver.archiveRootObject(self.folders, toFile: path)
    }
    catch
    {
        Swift.print("Error storing bookmarks")
    }
}

推荐阅读