swift - 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 {
}
}
}
解决方案
我正在使用以下代码来获取文件的图标。这非常可靠:
static func getIconForUrl(_ path: String) -> NSImage?
{
return NSWorkspace.shared.icon(forFile: path)
}
推荐阅读
- apache - 如何告知用户信任新 CA 颁发的服务器证书?
- javascript - 脚本和样式不在 functions.php 中排队
- c++ - Getting Unchecked return value from library?
- cakephp - Auth.afterIdentify 没有触发
- python - 如何在 json 文件中查找和替换 unicode?
- vue.js - nuxt, ...mapState 值返回为未定义
- google-apps-script - 是否可以更新/替换特定幻灯片中的文本?
- javascript - 无法读取 null 的属性“addEventListener”-Chrome 扩展
- python - 求一个数的除数之和的问题
- list - Flutter Grid 具有固定高度和可变宽度的项目