首页 > 解决方案 > Swift:在 Mac 上检索文件图标时出现问题

问题描述

我使用以下代码来检索文件或文件夹的图标。然后在菜单中显示它们。我的问题是:某些文件,图标不显示(例如.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 {

        }


    }
}

标签: swiftmacos

解决方案


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

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

推荐阅读