Search code examples
swiftmacoseventsnsevent

Stop listening to NSEvent in Swift


I am trying to get NSEvent to stop listening to local event. Is there a way to access the event after creating it?(which is what I unsuccessfully tried in removeEvent)

    override func viewDidLoad() {
        super.viewDidLoad()

        NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: sayHello(event:))
    }

    func sayHello(event: NSEvent) -> NSEvent {
        print("Welcome")
        return event
    }
    
    @IBAction func removeEvent(_ sender: NSButton) {
        let event  = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: sayHello(event:))

        NSEvent.removeMonitor(event)
    }

Solution

  • Just create a reference to your event monitor adding an instance property to your view controller and remove it with your button action:

    var monitor: Any?
    
    func sayHello(_ event: NSEvent) -> NSEvent {
        print(#function)
        return event
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: sayHello)
    
    }
    
    @IBAction func removeEvent(_ sender: NSButton) {
        if let monitor = monitor {
            NSEvent.removeMonitor(monitor)
        }
    }