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.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on June 7, 2020
Image placeholder

Keep reading

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

May 25, 2019 Object oriented design in Java

Java would have been fully Object Oriented if it didn’t have the primitive types like int, float, boolean, etc. However, it is mostly Object Oriented so you may go through this post if you’re new to Object-Oriented Programming.

March 2, 2020 My Mining cum Gaming PC

I have always yearned for the best gaming PC that could run all games at full settings and when I came to know about crypto mining, I thought I could hit two targets with one arrow.

review unboxing gadget November 20, 2020 Unboxing and Review of UE Megablast

I got the UE Megablast from Amazon as it was on a Prime deal. Normally, it costs around €160-€220 in Europe but I got it for €110 because of this offer. This is the most expensive Bluetooth speaker from UE. In this blog post, I would do the unboxing as well as give my reviews as I’ve been using it for around two months now.