Swift:在 Mac 上检索文件图标时出现问题

标签 swift macos

我使用以下代码来检索文件或文件夹的图标。然后在菜单中显示它们。我的问题是:有些文件,图标不显示(例如.txt文件)。文件夹和一些其他文件的图标仍然显示。这个问题的可能原因是什么?

// menuItem.Title: display name for file/folder
// menuItem.Content: full path of file/url


let menuItem = NSMenuItem(title: item.Title, action: #selector(AppDelegate.openLocal(_:)), keyEquivalent: "")

let requiredAttributes = [URLResourceKey.effectiveIconKey]


if let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: item.Content), includingPropertiesForKeys: requiredAttributes, options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants], errorHandler: nil) {

    while let url = enumerator.nextObject() as? URL {

        do {
            let properties = try  (url as NSURL).resourceValues(forKeys: requiredAttributes)

            let icon = properties[URLResourceKey.effectiveIconKey] as? NSImage  ?? NSImage()
            menuItem.image = icon

        }
        catch {

        }


    }
}

最佳答案

我正在使用以下代码获取文件的图标。这非常可靠:

static func getIconForUrl(_ path: String) -> NSImage?
{
    return NSWorkspace.shared.icon(forFile: path)
}

关于Swift:在 Mac 上检索文件图标时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785776/

相关文章:

iOS 和本地通知

matrix - Swift - CGAffineTransformInvert : singular matrix. UITextView & iAd

ios - Swift:如何在动态 UITableView 中使用静态单元格

android - 无法使用 adb (Mac OS X 10.7.5) 连接到 LG 手机

linux - 如何从远程 ssh 连接上运行的 tmux(复制模式)复制到本地剪贴板

ios - Xcode 仪器 - "This instrument does not support OSX"

ios - 任务排序

ios - 将 subview 添加到 tableViewController 中的主视图将 subview 添加到 TableView 而不是 swift 中的 View

mysql - Mac OSX/MySQL 5.6.19 上为 "Mysql2::Error: Lost connection to MySQL server during query"

python - Pip 和 Python 在模块位置上存在分歧