How to run AppleScript commands in Swift

Hello, Swift community.

I'd like to learn Swift after using Xojo (and RealBasic and Visual Basic and AppleSoft) since forever ago. I have an app that I'll be converting from Xojo to Swift, and there's a feature that I have to confirm can be done in Swift before I start the migration.

How do I run AppleScript commands in Swift.
And I don't mean how to run a script. My app has to generate dynamic AppleScript based on changing conditions and parameters. In Xojo, I can create an AppleScript object, I can define a string as a series of AppleScript commands. I can "compile" the object with the string. And then I can execute the object.
Can I accomplish that with Swift?

I've seen some articles about an NSAppleScript object that can be executed, but I'm not sure if I understand it. From what I can tell, does the NSAppleScript have a property named Source that I can assign my string to and execute the NSAppleScript object?

And if I write an app that is going to run AppleScript commands, do I need to learn about sandboxing and entitlements, or does Swift make that easier? Is there a link anyone recommends with a good explanation and examples of how I will be able to run scripts to modify an app like iTunes in Swift?

I can "compile" the object with the string. And then I can execute the
object. Can I accomplish that with Swift?

Yes. NSAppleScript is the easiest way to do this but Swift also has access to the whole stack of lower-level APIs that underpin this.

And if I write an app that is going to run AppleScript commands, do I
need to learn about sandboxing and entitlements … ?

Yes. AppleScript is based on Apple events, and sandboxing affects all code that sends Apple events, regardless of the source language.

ps These questions are very Apple specific and thus kinda off topic for Swift Forums (where the focus is on the Swift language itself). If you have follow-up questions I recommend that you start a new thread over on Apple Developer Forums. Make sure to tag it with AppleScript so that I see it go by.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes

Thank you for the answer and for the redirect.
Chuck

Terms of Service

Privacy Policy

Cookie Policy