如何使一个按钮在快速触发applescript?



我正在通过修改这个程序的代码为自己制作一个mac菜单栏应用程序

我想我的swift程序运行applescript时,菜单栏菜单按钮被按下,阅读一点后,我发现我需要看看像NSAppleScript或AppleScriptObjC的东西,但我找不到一个清晰的易于遵循的例子,为一个完整的初学者像我

现程序extreamly简单,只有这

需要对我的代码做什么更改以保留与以前相同的按钮功能,但只是添加,如果一个点击它触发/运行applescript?(代码- xcode swift app和applescript在下面)

applescript代码:

if running of application "System Preferences" then
try
tell application "System Preferences" to quit
on error
do shell script "killall 'System Preferences'"
end try
delay 0.1
end if
repeat while running of application "System Preferences" is true
delay 0.1
end repeat
tell application "System Preferences" to ¬
set the current pane to pane id ¬
"com.apple.preferences.sharing"
tell application "System Events"
tell front window of application process "System Preferences"
repeat until (exists checkbox 1 of row 5 of table 1 of scroll area 1 of group 1)
delay 0.01
end repeat
click checkbox 1 of row 5 of table 1 of scroll area 1 of group 1
delay 0.1
end tell
end tell
tell application "System Preferences" to quit

xcode应用代码:

class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem!
func applicationDidFinishLaunching(_ aNotification: Notification) {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let button = statusItem.button {
button.image = NSImage(systemSymbolName: "1.circle", accessibilityDescription: "1")
}
setupMenus()
}
func setupMenus() {
// 1
let menu = NSMenu()
// 2
let one = NSMenuItem(title: "One", action: #selector(didTapOne) , keyEquivalent: "1")
menu.addItem(one)
let two = NSMenuItem(title: "Two", action: #selector(didTapTwo) , keyEquivalent: "2")
menu.addItem(two)
let three = NSMenuItem(title: "Three", action: #selector(didTapThree) , keyEquivalent: "3")
menu.addItem(three)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
// 3
statusItem.menu = menu
}
// 1
private func changeStatusBarButton(number: Int) {
if let button = statusItem.button {
button.image = NSImage(systemSymbolName: "(number).circle", accessibilityDescription: number.description)
}
}
@objc func didTapOne() {
changeStatusBarButton(number: 1)
}
@objc func didTapTwo() {
changeStatusBarButton(number: 2)
}
@objc func didTapThree() {
changeStatusBarButton(number: 3)
}
}

有几个选项,但我认为"权利"方法是使用NSAppleScript:

import Foundation
let ascr = "tell application id "MACS" to reveal some item in the first Finder window"
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: ascr) {
if let scriptResult = scriptObject
.executeAndReturnError(&error)
.stringValue {
print(scriptResult)
} else if (error != nil)  { 
print("error: ",error!)
}
}

如果你不想将AppleScript代码作为字符串值包含在你的Swift代码中,你可以从文件URL中初始化脚本对象:

var error: NSDictionary?
let scptURL = URL(fileURLWithPath:"/path/to/scpt.applescript")
if let scriptObject = NSAppleScript(contentsOf:scptURL, error:&error) {
.
.
.

相关内容

  • 没有找到相关文章

最新更新