I am working on a macOS application, and I need to obtain the same file icons as displayed in Finder for various file types such as PDF, DOC, and others. I have tried using the following Swift code snippet:
let icon = NSWorkspace.shared.icon(forFile: path)
Unfortunately, this approach doesn't seem to work as expected for specific file types, like PDF and Word documents. Instead of obtaining the correct icons as displayed in Finder, I get a default white icon for these files.
I have tried several alternative solutions, but none have yielded the desired results. I would appreciate any suggestions or guidance on how to obtain the correct file icons for these file types, consistent with what is displayed in Finder.
First image (what I got): This is the file icon I obtained using the provided code. Notice that it is different from the one displayed in Finder, as it shows a default white icon instead of the expected file type icon.
Second image (what Finder displays): This is the icon for the corresponding file as displayed in Finder. This is the icon we want to obtain through our code.
Of course, I saved the obtained icon as a file using the following code. I'm not sure if this is related to the issue or not:
if let iconDataResized = icon.tiffRepresentation {
if let resizedImageData = NSBitmapImageRep(data: iconDataResized)?.representation(using: .png, properties: [:]) {
let iconFileURL = FileManager.default.temporaryDirectory.appendingPathComponent("test.icns")
try? FileManager.default.createDirectory(at: iconFileURL, withIntermediateDirectories: true, attributes: nil)
try? resizedImageData.write(to: URL(fileURLWithPath: iconFileURL.path), options: .atomic)
}
}
I have also tried this approach: let icon = NSWorkspace.shared.icon(forFileType: url.pathExtension)
but the result is the same as before.
Thank you in advance for your help.