Use HotKey Library in SwiftUI

436 Views Asked by At

I'm trying to use this library: soffes/HotKey in an SwiftUI Application for MacOS. The author describes the usage as follows:

  1. Set up Hotkey:
let hotKey = HotKey(key: .r, modifiers: [.command, .option])
  1. set the keyDownHandler and get callbacks for when your hot key is pressed:
hotKey.keyDownHandler = {
  print("Pressed at \(Date())")
}

My problem is that I don't know where I have to put the Handler. Any Ideas?

2

There are 2 best solutions below

0
On BEST ANSWER

Okay so I figured it out. The keyDownHandlerreally just defines what should happen when a hotkey is pressed so you can just put it into the .onAppear {} after your body View

0
On

I ran into this same problem; I was initializing a hotkey inside my appDelegate's applicationDidFinishLaunching function. I had it declared locally and I think it was getting garbage collected.

The fix for me was to make a hotKey property on my appDelegate (although I'm sure you could do the same on any root view or scene if you aren't using an appDelegate) and assign my hotKey to it:

class AppDelegate: NSObject, NSApplicationDelegate {

    var hotKey: HotKey?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let hotKey = HotKey(key: .six, modifiers: [.command, .option])
        hotKey.keyDownHandler = {
            print("Got hotkey at \(Date())")
        }
        
        self.hotKey = hotKey
    }
}