12

I am developing a Mac app using Swift 4 which only runs as an Agent (it only has a menu in the tray). I'm completely new to Swift.

I want it to respond to keyboard shortcuts, but the basic shortcuts (see picture) only work when the app has focus (in my case, when the menu is being clicked).

screenshot

So what I need is for my app to respond to system-wide keyboard shortcuts.

I've tried:

  • HotKey but it doesn't seem to be compatible with Swift 4, or perhaps I can't use Swift Package Manager
  • this answer but again Swift 4 raises several errors that I couldn't solve

Has anyone done it?

foucdeg
  • 815
  • 1
  • 7
  • 24
  • 1
    I don't specifically know how it's done in Swift, but years ago I wrote Objective-C code to do this: https://github.com/mdippery/blackout/blob/master/Source/BOApplication.m#L65 I haven't tested it on the latest OS but I think it still works. – mipadi Dec 11 '17 at 20:17
  • I think HotKey uses similar APIs, so it probably still works. Anyway, I solved my problem. Thanks. – foucdeg Dec 11 '17 at 21:57

2 Answers2

5

So I ended up getting it to work with HotKey:

  • by using Carthage as a package manager instead of SPM
  • and by not using HotKey's example code from their README, which for some reason didn't work for me, but the one in their example app.

It works great!

foucdeg
  • 815
  • 1
  • 7
  • 24
5

I made a Swift package that makes this very easy:

import KeyboardShortcuts

extension KeyboardShortcuts.Name {
    static let startFiveRounds = Self("startFiveRounds", default: .init(.t, modifiers: [.command, .option]))
}

@main
final class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ notification: Notification) {
        KeyboardShortcuts.onKeyUp(for: .startFiveRounds) {
            // …
        }
    }
}

Even though you already solved your problem, I think this could be useful for other people having the same problem.

I would also recommend letting the user pick their own keyboard shortcut instead of hardcoding it. My package comes with a control where the user can set their preferred shortcut.

Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232