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. ✌️

Ram Patra Published on June 7, 2020
Image placeholder

Keep reading

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

January 30, 2020 Stripe Interview for Software Engineer in Dublin

For those who may not know Stripe, it is a complete payments platform. It provides a suite of payments API that powers commerce for online businesses of all sizes.

February 16, 2020 Hubspot Interview for Senior Software Engineer

I applied to Hubspot directly on their website after seeing an open position in their Products team on LinkedIn or Stackoverflow Jobs, I do not exactly remember which one, in Dublin.

May 14, 2019 Variables and Literals in Java

Variables are devices that are used to store data, such as a number, or a string of character data so that we can manipulate them later in our program.