为它编写AppleScript是很好的,当它100%工作时,直接运行脚本。为了将其应用到菜单栏应用程序中,我尝试在线搜索,找到的唯一答案是以下链接:
Can you execute an Applescript script from a Swift Application
script: /Users/username/Documents/myscript.scpt: Operation not permitted
我的代码如下:
let proc = Process()
proc.launchPath = "/usr/bin/script"
proc.arguments = ["/Users/username/Documents/myscript.scpt"]
proc.launch()
我尝试了另一种解决方案,这次使用的是NSAppleScript:
let myAppleScript = "tell application \"System Events\" \ntell appearance preferences to set dark mode to not dark mode \nend tell"
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: myAppleScript) {
if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(&error) {
print(output.stringValue)
} else if (error != nil) {
print("error: \(error)")
}
}
但是这次我得到了一个错误:
error: Optional({
NSAppleScriptErrorAppName = "System Events";
NSAppleScriptErrorBriefMessage = "Application isn\U2019t running.";
NSAppleScriptErrorMessage = "System Events got an error: Application isn\U2019t running.";
NSAppleScriptErrorNumber = "-600";
NSAppleScriptErrorRange = "NSRange: {86, 9}";
})
但是如果我将脚本更改为更简单的内容,例如“display notification\”test\“,那么第二种解决方案就可以完美地工作。