I have a simple Swift app that needs to be able to control and send keystrokes to Mail.app. In pure AppleScript I'd do something like:
tell application "Mail"
activate
tell application "System Events" to keystroke "2" using command down
I've read Apple's Scripting Bridge Programming Guide and Communicating with Apps using AppleScript and Swift so I'm able to do this in Swift:
if let application = SBApplication(bundleIdentifier: "com.apple.Mail") {
let mailApplication = application as MailApplication
...
What I don't understand is how I can replicate AppleScript's tell application "System Events" to keystroke ... functionality in Swift. "System Events" isn't an SBApplication so I can't get a reference to it the same way I can Mail.app.
No need to emulate keystrokes using GUI Scripting, which is brittle and flaky. While not exactly obvious from Mail’s dictionary (which is a mess), you can use AppleScript to select mailboxes directly.
The trick is to manipulate the
selected messagesproperty of the frontmostmessage viewerobject.The
applicationclass defines properties containing references to the standard mailboxes (inbox,outbox,drafts mailbox, etc):Or you can refer to custom mailboxes by name:
(To find out the names of custom mailboxes, use
tell application "Mail" to get name of every mailbox.)