0

I am relatively new to Swift and currently working on a text snippet app. For that, the app should run in the background (as a menu bar application), get the pressed keys and append them to a string.

The following implementation works fine but is not allowed to be uploaded to the AppStore (Because of the permission) When using this permission I have to select the App manually and it does not appear in a list of applications. (Called in OnAppear when the App is launched)

func getPermissions() {
        AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue(): true]          as CFDictionary)
}

I got the following code from a tutorial

@MainActor class ExpanderModel: ObservableObject {
    
    @Published var text = ""
    
    init () { 
        
        NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]) { _ in
            self.text = ""
        }
        
        NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { (event) in
            guard let characters = event.characters else { return }
            //print(characters, event.keyCode)
            if event.isDelete && !self.text.isEmpty {
                self.text.removeLast()
            } else if event.keyCode > 100 {
                self.text = ""
            } else {
                self.text += characters
            }
        }
    }

I found out that getting the pressed keys by using CGEvents should be allowed but after hours of trial and error I couldn’t really get anything to work. (I have seen some similar questions like this one but also couldn't get anything to work.)

How would a similar implementation look like using CGEvent and which permissions do I need to still have a sandboxed app? I think it still needs some type of permission for accessibility.

It would be super helpful if anyone has an idea how to solve the problem - Many thanks in advance.

0 Answers0