Show/Hide dock icon on macOS App

If you are looking for just hide dock icon on macOS App, check it here How to hide the Dock icon.

Sometimes this needs to be configurable, like Dash and CloudApp.

It’s easy to get it done, just setActivationPolicy to accessory or regular which represent hide and regular respectively. But there is some unexpected side effect:

For Dash, it will show its icon at dock first when launching, and hide it programmatically after launch. Because show dock icon is set to true by default, and there is not such LSUIElement in its Info.plist.

Dash icon appears for a second when launching.

To avoid it, you have to set LSUIElement to YES and you can still have icon shown in dock by default by just setActivationPolicy to regular.

For some reason, when setActivationPolicy to regular, all the windows will hide automatically, which is not what we want normally. To keep window while hide dock icon, like CloudApp:

The window is flashing when hide the icon. Because hide the icon will hide the window as well. So probably CloudApp enforce activate the app by using NSApp.activate(ignoringOtherApps:true) in main thread. And as you can see, there will be more than one dock icon as you click fast.

To solve the first issue, you can make the window canHide = false though this will have side effect like the window menu(on the top left of the menu bar) won’t show until you reopen the window. I think it’s acceptable at least it’s better than what it was before.

To solve the second issue, just set a scheduledTimer like 0.3 second, and then every time user change the dock icon setting, invalidate the timer and reschedule it.

var timer: Timer?
func showDockIconClicked(_ sender: Any) {
    timer?.invalidate()
    timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false, block: { _ in
        // toggle dock icon shown/hidden.
    })
}

That’s it! Here is the result:

If you know a more elegant way to do it, please let me know!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.