Search code examples
swiftmacoscommand-lineappkit

Change command line app icon programmatically


I've created a swift command line app for macOS (WITHOUT XCODE, just a simple .swift file), used to build a macOS installer.

When I run the app with sudo swift install.swift, the app is opened with an icon with a terminal app design like this:

Icon

I want to change that icon from the code, would that possible? I'm using Appkit.


Solution

  • You can change the icon by setting NSApplication's applicationIconImage property. That is, if you can obtain an image. Since your program isn't a bundled app, it won't be easy to provide an image with it.

    There will be an unavoidable visual glitch when your program exits, though. Its icon will revert to that "exec" icon as it shrinks in the Dock before vanishing. Also, if the icon ends up in the Dock's recently-used applications section, it will be the "exec" icon, there, too. In other words, the icon set programmatically persists only as long as the program runs.

    By the way, it's distinctly unwise to run the high-level frameworks with root privileges. It opens a large attack surface that's not really audited for security. You probably want to separate your program into a user app and a privileged helper.