Swift/AppleScript: Cannot run apple script from Sw

2020-03-30 02:12发布

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条回答
▲ chillily
2楼-- · 2020-03-30 02:29

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.

查看更多
登录 后发表回答