Swift 运行可执行文件时不记录按键事件

Swift 运行可执行文件时不记录按键事件,swift,macos,Swift,Macos,我从互联网上收集了一些代码,用于监控全球密钥关闭事件 当我通过Xcode运行它时,它工作得很好。问题是当我通过终端运行它时,它不会捕获任何事件。我已经在Xcode和Terminal的设置中启用了可访问性 代码如下: func handlerEvent(aEvent: (NSEvent!)) -> Void { let stringBuilder = aEvent.characters! print(stringBuilder, separator: "", termina

我从互联网上收集了一些代码,用于监控全球密钥关闭事件

当我通过Xcode运行它时,它工作得很好。问题是当我通过终端运行它时,它不会捕获任何事件。我已经在Xcode和Terminal的设置中启用了可访问性

代码如下:

func handlerEvent(aEvent: (NSEvent!)) -> Void {

    let stringBuilder = aEvent.characters!
    print(stringBuilder, separator: "", terminator: "")


}

// MARK: Event Monitor
func listenForEvents() {
    let mask = (NSEventMask.keyDown)
    _ = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handlerEvent)
}

func acquirePrivileges() -> Bool {
    let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String : true]
    let accessEnabled = AXIsProcessTrustedWithOptions(options)

    if !accessEnabled {
        print("Access Denied")
    }

    return accessEnabled
}

class ApplicationDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
                if acquirePrivileges()
        {
            print("Access Granted")
        }
        print("Starting logging")

        listenForEvents()
    }
}


let application = NSApplication.shared()

let applicationDelegate = ApplicationDelegate()
application.delegate = applicationDelegate
application.activate(ignoringOtherApps: true)
application.run()

这必须是命令行应用程序吗?您通常只能将应用程序捆绑包(即带有Info.plist和应用程序标识符的东西)注册到全局监视器。您可能会注意到,当您运行此应用程序时,它会要求授权Xcode或Terminal,因为这是您正在运行的应用程序。Xcode将事件转发给您,而终端可能不会


如果您可以将其作为常规应用程序包(即使没有UI),也应该可以。

谢谢您的建议。我认为这是在没有UI的情况下通过构建来完成工作的唯一方法。