本文由 简悦 SimpRead转码, 原文地址 hhas.bitbucket.io
SwiftAutomation 可让您使用苹果公司的 Swift pr...... 来控制 "AppleScriptable "macOS 应用程序。
什么是 SwiftAutomation?
通过 SwiftAutomation,您可以使用苹果公司的Swift 编程语言控制 "AppleScriptable "macOS 应用程序。SwiftAutomation 使 Swift 成为 Mac 自动化 AppleScript 的真正替代品。
例如,要获取 TextEdit 中最顶层文档第一段的值:
let result = try TextEdit().documents[1].paragraphs[1].get() as String
这相当于 AppleScript 语句:
tell application id "com.apple.TextEdit" to get paragraph 1 of document 1
或者在 TextEdit 中创建一个新的 "Hello World!
// tell application id "com.apple.TextEdit"
// make new document with properties {text:"Hello World!"}
// end tell
let textedit = TextEdit()
try textedit.make(new: TED.document, withProperties: [TED.text: "Hello World!"])
获取 SwiftAutomation
要将 SwiftAutomation 资源库 克隆到自己的机器上:
git clone https://bitbucket.org/hhas/swiftae.git
最低要求:macOS 10.11 和 Xcode 8.1/Swift 3.0.1。
在学习 SwiftAutomation 教程并编写每次运行时都会编译和执行的 #!/usr/bin/swift
"脚本 "时,最简单的入门方法是构建 SwiftAE 项目的 Release 目标,然后在 /Library/Frameworks
中创建指向 SwiftAutomation 和 MacOSGlues 框架的 symlink:
cd /Library/Frameworks
sudo ln -s /path/to/Build/Products/Release/SwiftAutomation.framework
sudo ln -s /path/to/Build/Products/Release/MacOSGlues.framework
并在 /Applications
中创建指向 AppleScriptToSwift 应用程序的符号链接:
cd /Applications
sudo ln -s /path/to/Build/Products/Release/AppleScriptToSwift.app
使用这些框架时,请记住 Swift 尚未提供稳定的 ABI,因此 Swift 程序只能导入使用 完全 相同版本 Swift 编译的框架。因此,每当安装新版本的 Xcode/Swift 时,您都必须重建这些框架。[待办事项:如何在 CLI 和 GUI 应用程序中嵌入框架?]
在您开始之前...
为了有效使用 SwiftAutomation,您需要了解 Apple 事件与 Swift/Cocoa 对象系统之间的差异。
与 COM 和 Distributed Objects 等其他进程间通信系统熟悉的面向对象方法不同,Apple 事件 IPC 基于远程过程调用和一流查询的组合,这有点类似于在 XML-RPC 中使用 XPath。
虽然 SwiftAutomation 使用了类似面向对象的语法以提高简洁性和可读性,但与 AppleScript 一样,它的行为也符合 Apple 事件规则。因此,Swift 用户会发现 SwiftAutomation 中的某些工作方式与他们习惯的方式不同。例如
-
对象元素的索引是1开头,而不像 Swift 数组那样索引是0开头。
-
引用应用程序对象的属性不会自动返回该属性的值(需要使用 get 命令)。
-
许多应用程序允许一条命令同时对多个对象执行操作,这在操作大量应用程序对象时能带来显著的性能优势。(相反,发送大量命令逐个操作单个对象会严重降低性能)。
本手册第 2 章和第 3 章进一步介绍了 Apple 事件 IPC 的工作原理,以及 SwiftAutomation 桥接教程。第 4 章和第 10 章介绍了如何生成用于控制特定应用程序的胶水文件。第 5 章至第 9 章介绍了 SwiftAutomation API,第 11 章讨论了优化性能的技巧。