Loading...

How to quit or close an app in macOS using Swift?

question macOS swift
Ram Patra Published on August 14, 2020

You can quit or exit an app with:

NSApp.terminate(self)

If you’re making a macOS menu bar app in Swift and have an option in the dropdown menu to quit the app then your code would look something like:

NSMenuItem(title: "Quit", action: #selector(quitClicked), keyEquivalent: "q")

Menu Bar Item

@objc private func quitClicked() {
    NSApp.terminate(self)
}

Function invoked when a user clicks on the menu item

Note: Do not forget to add @objc in front of the function so that it can be called from #selector.

Ram Patra Published on August 14, 2020
Image placeholder

Keep reading

If this article was helpful, others might be too

question macOS swift March 14, 2021 How to ignore mouse events in a view or window in macOS?

You can ignore mouse events in a window/view by adding just a single line of code.

question macOS swift August 6, 2020 How to open an app's window on top of all others in Swift?

You can open your app’s window on top of all other open application windows with the below code:

June 7, 2020 How to add Global Key Shortcuts to your macOS app using MASShortcut

Adding Global Keyboard Shortcuts to your macOS app can be a pain as there isn’t a Cocoa API for the same. You would have to rely on the old, most of which are deprecated, Carbon API.