SwiftUIAppleScript icon indicating copy to clipboard operation
SwiftUIAppleScript copied to clipboard

Different Approach of AppleScriptRunner (not an issue)

Open stklieme opened this issue 2 years ago • 1 comments

Hi Mark,

I wrote – also – an AppleScriptRunner in Swift which is based on Application Scripts and NSUserAppleScriptTask. It uses async/await, it's generic and is encapsulated in an actor. All conversions from and to NSAppleEventDescriptor are performed in the actor. It conforms even to Sendable.

AppleScriptRunner.zip

There is an enum Handler, the cases must correspond with the handler names in the script, the fileName is the name of the application (here hard-coded for test purposes).

There is a method to copy the script from the application bundle to the Application Scripts folder of the application (if not present).

Just call

Task {
    do {
        let runner = AppleScriptRunner()
        try await runner.installScript()
    } catch { print(error) }
}

The AppleScript handler the code is referring to is the simple handler

on finderSelection
    tell application "Finder" to return selection as alias list
end finderSelection

Call it in a Task or async environment, the method name can be arbitrary

func finderSelection() async throws -> [URL] {
    let runner = AppleScriptRunner()
    return try await runner.run(handler: .finderSelection)
}

Necessary parameters can be passed as Swift types in the parameters parameter, all supported types conform to DescriptorConvertible.

Side note: I know that there is an async version of execute(withAppleEvent:) but it violates the actor rules, therefore the Continuation.

Feel free to use the code wherever you want. It's not particularly related to SwiftUI. TheHandler enum can be extended to support multiple scripts but then the installScript method must be adjusted to check/copy all scripts.

If you find bugs or improvements let me know.

Regards

Stefan

(StefanK on MacScripter)

stklieme avatar Mar 08 '23 15:03 stklieme

Thanks for this. My code was created before Swift's new async await stuff came into existence. I'll see how I can improve things. I still have plans for an app that uses all of this but time has not permitted it.

Beware of NSUserAppleScriptTask as it does not support generic OSA scripts and thus JavaScript for Automation.

alldritt avatar Mar 11 '23 00:03 alldritt