问题
I try to run AppleScript command from Swift code like this:
var appleScriptCmd = "tell application \"System Events\" to make login item at end with properties {path:\"" + appPath + "\", hidden:false, name:\"Some App\"}";
var appleScriptCmd2 = "tell application \"System Events\" to set visible of process \"Safari\" to false";
and then I have tried both:
let script = NSAppleScript(source: appleScriptCmd2)!;
var errorDict : NSDictionary?
script.executeAndReturnError(&errorDict)
if errorDict != nil { print(errorDict!) }
or older approach:
Process.launchedProcess(launchPath: "/usr/bin/osascript", arguments: ["-e", appleScriptCmd])
neither works and simultaneously both commands I have tried are working from Terminal program using osascript -e "some command" tool.
回答1:
Since your app is sandboxed (Project Settings > Capabilities turn on App Sandbox) you have three options:
- Add temporary entitlements for the applications you want to use.
- Put your scripts in the appropriate directory in
~/Library/Application Scripts/
and use NSUserAppleScriptTask. - Implement an AppleScriptObjC bridge and run the AppleScript code from the ASOC framework (requires also an Objective-C bridging header file).
In a sandboxed app NSAppleScript
refuses to work.
来源:https://stackoverflow.com/questions/44027241/swift-applescript-cannot-run-apple-script-from-swift-code