AppleScript 模拟按键输入 control + 空格
tell application "System Events"
key code 49 using control down
end tell
Swift 调用 AppleScript
let applesript = """
tell application "System Events"
key code 49 using control down
end tell
"""
if let script = NSAppleScript(source: applesript) {
var error: NSDictionary?
script.executeAndReturnError(&error)
if let err = error {
print("[Applescript] NSAppleScript.executeAndReturnError(): \(err)")
}
}
添加权限
勾选 Apple Events 权限
在 TARGES
->Signing & Capabilities
->Hardened Runtime
可以找到
添加申请描述
在 TARGES
->Info
中添加一个字段 Privacy - AppleEvents Sending Usage Description
,描述在申请权限时用户看到的信息
如果没有这个字段,系统就不会弹出授权界面,也就无法获得权限
小坑
完成以上步骤后,运行程序时会弹出两个授权界面
授权后就能模拟按键输入了
如果调用失败可能是因为开启了沙盒,试着将其关闭