Loading a local .scpt file in my Swift project causes error

Published

I’m testing out a Mac app, trying to load my hello.scpt file which is in my Xcode project in the /scripts directory

# even though it's in the scripts folder, `path` will be nil unless the resource value is "hello"
let path = Bundle.main.path(forResource: "hello", ofType: "scpt")
let url = URL(fileURLWithPath: path!)
let scriptObject = try? NSUserAppleScriptTask(url: url)
scriptObject?.execute { handler in
     print(handler)
}

Error:

Optional(Error Domain=NSCocoaErrorDomain Code=257 "The file
“hello.scpt” couldn’t be opened because you don’t have permission to
view it."
UserInfo={NSURL=file:///Users/me/Library/Developer/Xcode/DerivedData/app-gidwjssyedvwuyfcncsjkfroqdjp/Build/Products/Debug/myApp.app/Contents/Resources/test.scpt,
NSLocalizedFailureReason=Script file is not in the application scripts
folder.})

I tried vadian’s response below, creating a folder called NSApplicationScriptsDirectory which seems weird. Also tried specifying in the Info.plist NSApplicationScriptsDirectory as the key and different variants to the ./scripts/ file as the key but no luck here.

This is a simple sandboxed app with a Hello World script that just prints "Hello world" to stdout

How can I load this AppleScript in and get it to work without the error?

Thanks!

Edit: I’ve also tried putting it in my ~/Library/Scripts folder as hello.scpt but that doesn’t work either

Source: Swift Questions

Published
Categorized as applescript, macos, swift Tagged , ,

Answers

The error is pretty clear:

Script file is not in the application scripts folder


From the documentation of NSUserAppleScriptTask

The NSUserAppleScriptTask class is intended to run AppleScript scripts from your application. It is intended to execute user-supplied scripts and will execute them outside of the application’s sandbox, if any.

The class is not intended to execute scripts built into an application; for that, use one of the NSTask classes. If the application is sandboxed, then the script must be in the NSApplicationScriptsDirectory folder. A sandboxed application may read from, but not write to, this folder.

If you simply need to execute scripts without regard to input or output, use NSUserScriptTask, which can execute any of the specific types. If you need specific control over the input to or output from the script, use this class.


Greta Stracke

Leave a Reply

Your email address will not be published. Required fields are marked *

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq