沙盒里面运行AppleScript可不是那么简单,如下
项目的.entitlements文件记得要搞成这样,弄完了别忘了clean your project folder然后再测试
<key>com.apple.security.automation.apple-events</key>
<true/>
<key>com.apple.security.temporary-exception.apple-events</key>
<array>
<string>com.apple.systemevents</string>
</array>
plist文件
<key>NSAppleEventsUsageDescription</key>
<string></string>
把文件写入到
var dir = FileManager.default.urls(for: .applicationScriptsDirectory, in: .userDomainMask)[0]
这里面
写入的代码:
func check() -> Bool {
let path = NSSearchPathForDirectoriesInDomains(.applicationScriptsDirectory, .userDomainMask, true)[0]
let file = "\(path)/你写好的脚本编辑器的内容.scpt"
return FileManager.default.fileExists(atPath: file)
}
func install() {
if !check() {
let panel = NSSavePanel()
panel.title = "保存AppleScript"
panel.message = "请保存AppleScript文件至Application Scripts目录才可使用"
// panel.allowedFileTypes = ["json"]
panel.nameFieldStringValue = "你写好的脚本编辑器的内容.scpt"
panel.directoryURL = FileManager.default.urls(for: .applicationScriptsDirectory, in: .userDomainMask)[0]
panel.canCreateDirectories = false
panel.delegate = self
if panel.runModal() == .OK {
if let url = panel.url {
// 这里是你的项目的脚本的resource文件
if let resourceUrl = Bundle.main.url(forResource: "你写好的脚本编辑器的内容", withExtension: "scpt") {
do {
let data = try Data(contentsOf: resourceUrl)
try data.write(to: url)
return
} catch {
panel.cancel(nil)
install()
}
}
}
}
panel.cancel(nil)
install()
}
}
运行脚本的代码:
var dict:NSDictionary?
var dir = FileManager.default.urls(for: .applicationScriptsDirectory, in: .userDomainMask)[0]
dir.appendPathComponent("你写好的脚本编辑器的内容.scpt")
let script = NSAppleScript(contentsOf: dir, error: &dict)
script?.executeAndReturnError(&dict)
print(dict)
帮助链接:
重要链接(必看):
https://www.jessesquires.com/blog/2018/11/17/executing-applescript-in-mac-app-on-macos-mojave/
国产:
https://www.foolishtalk.org/2019/11/10/%E5%9C%A8Mac-app%E4%B8%8A%E6%89%A7%E8%A1%8CAppleScript/