沙盒里面運行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)/你寫好的腳本編輯器的內(nèi)容.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 = "你寫好的腳本編輯器的內(nèi)容.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: "你寫好的腳本編輯器的內(nèi)容", 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("你寫好的腳本編輯器的內(nèi)容.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/
國產(chǎn):
https://www.foolishtalk.org/2019/11/10/%E5%9C%A8Mac-app%E4%B8%8A%E6%89%A7%E8%A1%8CAppleScript/