Search code examples
swiftmacosappkitnsworkspace

How to get a high resolution app icon for any application on a Mac?


Apple documentation specifies that NSWorkspace icon(forFile:) returns a 32x32 icon, but I'm not sure how to specify a different size.

This is a sample SwiftUI code I'm using to display the icon for XCode:

Image(
  nsImage: NSWorkspace.shared.icon(forFile: "/Applications/XCode.app/")
).renderingMode(.original)

Solution

  • One way I found is to use bestRepresentation. You should pass in the dimensions you want the image to be in (e.g. 1024x1024), and it will find you the best representation there is for that size.

    if let rep = NSWorkspace.shared.icon(forFile: "/Applications/XCode.app/")
        .bestRepresentation(for: NSRect(x: 0, y: 0, width: 1024, height: 1024), context: nil, hints: nil) {
    
    }
    

    Then you can just draw the NSImageRep, or create an NSImage using it:

    let image = NSImage(size: rep.size)
    image.addRepresentation(rep)