Loading...

How to add Global Key Shortcuts to your macOS app using MASShortcut

swift macOS mac
Ram Patra Published on June 7, 2020
Image placeholder

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.

Having said that, there’s some good news as a couple of awesome folks have released open-source libraries that make this task a breeze. Three of them that I know of are, MASShortcut, HotKey, and KeyboardShortcuts. The last one is new and released at the time of this writing.

Out of these 3 libraries, MASShortcut is written in Objective-C whereas others are written in Swift. Additionally, MASShortcut is the most advance among all and has more features. However, it currently supports installation through Cocoapods and Carthage only. Ergo, I had to put in some extra effort to make this library a Swift package so that I can install it via SPM and not via Cocoapods or Carthage. This is the final github repo https://github.com/rampatra/MASShortcut after I converted MASShortcut to a Swift package. You can use either the official one if you have no issues with Cocoapods or Carthage. Or, feel free to use my repo. I can try my best to keep it updated with the official one. Do note that most of the credit for this work goes to SDGGiesbrecht. He guided me from start to end as I had no experience with Objective-C for which I am very grateful to him.

How it looks?

This is quite impressive if you ask me as this view is the best out of all the 3 libraries. HotKey doesn’t even have a view.

How to install?

I am writing the steps to install this library via SPM.

  1. Copy the github repo url
  2. Go to Xcode > File > Swift packages > Add Package Dependency…
  3. Paste the repo URL and click next
  4. Choose the version or branch and click next

Usage

Create a MASShortcut Object
MASShortcut(keyCode: Int, modifierFlags: NSEvent.ModifierFlags)

where,
keyCode is the carbon keycode
modifierFlags is NSEvent.ModifierFlags

Register Default Shortcuts
MASShortcutBinder.shared()?.registerDefaultShortcuts(dict)

where, dict is a dictionary with key as the User Defaults key and value as the MASShortcut object

Note: The key here is important as you would need this to fetch the Shortcut, modify it, unregister it, and to bind it to the view.

Binding Shortcut with Action
MASShortcutBinder.shared()?.bindShortcut(withDefaultsKey: String!, toAction: (() -> Void)!)
Binding Shortcut to the View

Let’s say you have the view like:

@IBOutlet weak var shortcutKeyView: MASShortcutView!

You bind this view like:

shortcutKeyView.associatedUserDefaultsKey = String

where, String is the User Defaults key with which you first registered

Get KeyEquivalent of a Shortcut
func getKeyEquivalent(_ forCommand: Command) -> (String?, NSEvent.ModifierFlags)? {
    guard let masShortcut = MASShortcutBinder.shared()?.value(forKey: String) as? MASShortcut else { return nil }
    return (masShortcut.keyCodeStringForKeyEquivalent, masShortcut.modifierFlags)
}
Unregister Shortcut
MASShortcutBinder.shared()?.breakBinding(withDefaultsKey: String!)
Reset Shortcut to Default
UserDefaults.standard.removeObject(forKey: String)

One cool thing about this library is that it automatically handles key shortcut changes done by the user through the view. You do not have to write any code for it. Having said that, if you want to perform some tasks when a user changes the key shortcut, you can easily do it like below:

shortcutKeyView.shortcutValueChange = { view in
	// do your task here
}

Of course, there’s more to the MASShortcut API and I have only listed some of the basic and important ones. Please, feel free to comment if I’ve missed out any other useful APIs. I can surely update this post.

Lastly, if you want to see a live demo of how this works then you can check out Presentify on the Mac App Store. I have used this library for handling all of my Keyboard Shortcut needs and it has worked great so far. ✌️

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

KeyScreen

Show keypresses on your screen.

ToDoBar

Your to-dos on your menu bar.

SimpleFill

Fill forms using your right-click menu.

IconSim

Preview your Mac app icons.

Ram Patra Published on June 7, 2020
Image placeholder

Keep reading

If you liked this article, you may like these as well

January 25, 2020 How to know whether a user is using an adblocker

Adblocker detection is a nice feature to have, given that around 47% of the users now use ad blockers according to GlobalWebIndex.

November 28, 2019 How I made my blog

I made this blog using JAMStack. J stands for Javascript, A for APIs, and M for Markups. So, in short, a website built using HTML, CSS, and Javascript only and maybe accessing some APIs over HTTP can be said to be built with JAMStack and are generally called Static Websites.

September 5, 2025 Automatically generate appcast.xml and DMG files for your Mac app updates

In this blog post we will see how we can fully automate macOS app updates with Sparkle 2 + GitHub Actions + GitHub Pages. We will build, notarize, sign, auto-generate appcast.xml and DMG files, etc. using GitHub Actions whenever you create a new release (this can be changed to on commit too).

Like my work?

Please, feel free to reach out. I would be more than happy to chat.