Swift/AppleScript: Cannot run apple script from Swift code

孤人 提交于 2019-12-01 09:19:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!