SlideShare a Scribd company logo
Automate with Swift
CocoaConf DC, April 10, 2015
Tony Ingraldi
GitHub: tingraldi • Twitter: @TonyIngraldi
Itinerary
• Motivation: Why Automate?
• A bit of history
• Why Swift?
• Nuts and bolts
Show of Hands?
• Have you used…
• AppleScript?
• Automator?
• Other form of application scripting?
Why Automate?
• Improve productivity
• Avoid repetitive tasks
• Streamline workflows
• Opportunities for experimentation
• Add missing features to OS X apps!
Scriptable Applications
Demo
Sneak peak
Open Scripting Architecture
• Introduced way back in October 1993
• The state of the Mac looked like this
Beige!
Open Scripting Architecture
• Survived the transition to OS X
• Leveraged by OS X to launch applications, open
documents, etc.
• A standard mechanism for interapplication
communication
Language Options
• AppleScript (there from the beginning)
• JavaScript for Automation (as of Yosemite)
• Python (PyObjC, py-appscript)
• Ruby (RubyCocoa, RubyOSA)
• And now Swift!
Language Options
• AppleScript (there from the beginning)
• JavaScript for Automation (as of Yosemite)
• Python (PyObjC, py-appscript)
• Ruby (RubyCocoa, RubyOSA)
• And now Swift!
AppleScript
• A ā€œnatural languageā€ programming model
• Primarily geared toward being the ā€œglueā€
between apps
• Limited inherent functionality
AppleScript
• Can be frustrating to people who are fluent in
ā€œnormalā€ programming languages
• Verbosity is a hallmark
set fileName to "name.jpg"
set sansExtension to text 1 thru ((offset of "." in fileName) - 1) of fileName
Swift
• A ā€œprimaryā€ language
• Ready access to Cocoa
• Can run Swift scripts using #! convention
• A familiar coding style
let fileName = "name.jpg"
let sansExtension = fileName.stringByDeletingPathExtension
Scripting Bridge
• Introduced in Mac OS X Leopard (version 10.5)
• Provides high-level Objective-C access to
scriptable applications
• Can be leveraged in Swift, with a bit of extra
work
Scripting Bridge Recipe
• 1 part sdef
• 1 part sdp
• A pinch of manual intervention
• Automate to taste
Scripting Definition
• Scriptable applications include resources that
describe their scripting interface
• Can be in a variety of forms
• The sdef command-line utility extracts the
scripting definition
• Writes to standard output in XML format
Scripting Definition
• Using sdef
sdef /path/to/App.app > App.sdef
• For the most part, using sdef is ā€œrun and forgetā€
• Until you find out what’s wrong when you run sdp
• Some sdp warnings can be ignored
Scripting Definition
• Using sdp
sdp -fh --basename App App.sdef
Demo
sdef and sdp
Kicking the Tires
• Xcode
• Swift and ObjC command line targets
• Includes the header generated by sdp
• Experiment in main.swift and main.m
Demo
Kicking the tires in Xcode
Don’t Run with Scissors
• Using Objective-C header leads to pervasive
AnyObject typing
• Works, but can lead to ambiguity
• For properties, sometimes have to resort to
using valueForKey
• Sometimes leads to awkward method
invocation
An Alternative
• Create Swift protocols that cover the generated
Objective-C API
• šŸ‘ Supports rich set of types
• šŸ‘ API translation can be automated
• šŸ‘Ž Requires optional declaration of all
properties and methods
Objective-C Excerpt
@interface AcornApplication : SBApplication
@property (copy, readonly) NSString *name;
- (SBElementArray *) windows;
- (NSString *) taunt;
@end
SBObject
@objc public protocol SBObjectProtocol:
NSObjectProtocol {
func get() -> AnyObject!
}
SBApplication
@objc public protocol SBApplicationProtocol:
SBObjectProtocol {
func activate()
var delegate:SBApplicationDelegate! { get set }
}
Application Protocol
@objc public protocol AcornApplication:
SBApplicationProtocol {
optional var name: String { get }
optional func windows() -> SBElementArray
optional func taunt() -> String
}
extension SBApplication : AcornApplication {}
Putting it Together
import ScriptingBridge
@objc public protocol AcornApplication : … {…}
extension SBApplication : AcornApplication {}
let acorn = SBApplication
.applicationWithBundleIdentifier(
ā€œcom.flyingmeat.Acorn4"
) as! AcornApplication
acorn.taunt!()
Acorn Taunt
Plan of Attack
• Create frameworks for target applications
• Install in /Library/Frameworks
• Write scripts instead of compiled code
By the Way
• Playgrounds don’t fit well
• The Swift REPL could spontaneously combust at
any moment
• What’s a scripter to do?
• Use a text editor
• Edit, run, repeat
Script Invocation
• Hash-bang on the first line
#!/usr/bin/xcrun swift -F /Library/Frameworks
• chmod +x SomeScript.swift
A Little Help
https://github.com/tingraldi/SwiftScripting
• Header conversion utilities
• Sample Application Scripting Frameworks
• Sample Scripts
• Scripting Utilities Framework
Demo
A Scripting Framework
A Little More Help
import ScriptingBridge
@objc public protocol AcornApplication {…}
extension SBApplication : AcornApplication {}
let acorn = SBApplication
.applicationWithBundleIdentifier(
"com.flyingmeat.Acorn4"
) as! AcornApplication
acorn.taunt!()
A Little More Help
import ScriptingBridge
import AcornScripting // Acorn Swift protocols
let acorn = SBApplication
.applicationWithBundleIdentifier(
"com.flyingmeat.Acorn4"
) as! AcornApplication
acorn.taunt!()
A Little More Help
import ScriptingUtilities // Helper framework
import AcornScripting // Acorn Swift protocols
let acorn = Application(name: "Acorn")
as! AcornApplication
acorn.taunt!()
Where to Put Scripts?
• Short answer: anywhere
• Some applications have special script folders
• Scripting Menu
• Invoke via an Automator Service
Demo
Scripting Menu, etc.
Summary
• Automate for productivity
• Add ā€œmissing featuresā€
• Reinforce/leverage Swift expertise
Questions?

More Related Content

PDF
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
PDF
Functional Programming for Busy Object Oriented Programmers
PPTX
PUG Challenge 2016 - The nativescript pug app challenge
PPTX
Type Annotations in Python: Whats, Whys and Wows!
PDF
TypeProf for IDE: Enrich Development Experience without Annotations
PDF
LLVM Internal Architecture par Michel Guillet
PDF
Swift for back end: A new generation of full stack languages?
PDF
A Type-level Ruby Interpreter for Testing and Understanding
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
Functional Programming for Busy Object Oriented Programmers
PUG Challenge 2016 - The nativescript pug app challenge
Type Annotations in Python: Whats, Whys and Wows!
TypeProf for IDE: Enrich Development Experience without Annotations
LLVM Internal Architecture par Michel Guillet
Swift for back end: A new generation of full stack languages?
A Type-level Ruby Interpreter for Testing and Understanding

What's hot (20)

PDF
java8-patterns
PPTX
Roslyn
PPTX
PPTX
Ruby, the language of devops
PDF
A Taste of Pharo 7.0
Ā 
PDF
Variables in Pharo5
PPT
TypeScript for Alfresco and CMIS - Alfresco DevCon 2012 San Jose
PPTX
Why I don’t want to develop iOS apps in Objective C
PDF
Type Profiler: An Analysis to guess type signatures
ODP
Practical byteman sample 20131128
PDF
Crystal
PDF
Cookpad Hackarade #04: Create Your Own Interpreter
PPTX
Wonders of Golang
PDF
Functional Programming in JavaScript
PDF
Reflection in Pharo5
PPTX
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
PDF
Clang Analyzer Tool Review
PPT
Take Flight - Using Fly with the Play Framework
PDF
javerosmx-2015-marzo-groovy-java8-comparison
java8-patterns
Roslyn
Ruby, the language of devops
A Taste of Pharo 7.0
Ā 
Variables in Pharo5
TypeScript for Alfresco and CMIS - Alfresco DevCon 2012 San Jose
Why I don’t want to develop iOS apps in Objective C
Type Profiler: An Analysis to guess type signatures
Practical byteman sample 20131128
Crystal
Cookpad Hackarade #04: Create Your Own Interpreter
Wonders of Golang
Functional Programming in JavaScript
Reflection in Pharo5
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Clang Analyzer Tool Review
Take Flight - Using Fly with the Play Framework
javerosmx-2015-marzo-groovy-java8-comparison
Ad

Similar to CocoaConf DC - Automate with Swift - Tony Ingraldi (20)

PDF
Cocoapods and Most common used library in Swift
PPTX
Tech breakfast 18
PPTX
Swift programming language
PPTX
Swift: A parallel scripting for applications at the petascale and beyond.
PDF
Method Swizzling with Objective-C
PPTX
Server Side Swift
PPTX
PPT.pptxvkjvwbjbbikvhixhkiheihhiiihwxhhi
PDF
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
PDF
What’s new in Swift 5.2-5.3
PDF
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th E...
PDF
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
PDF
To Protect & To Serve
PPTX
iphone application development
PDF
What Makes Objective C Dynamic?
PPTX
Swift
PDF
Swift Tutorial Part 2. The complete guide for Swift programming language
PDF
Swift for-rubyists
PDF
Open Source Swift Under the Hood
PDF
Swift, a quick overview
Cocoapods and Most common used library in Swift
Tech breakfast 18
Swift programming language
Swift: A parallel scripting for applications at the petascale and beyond.
Method Swizzling with Objective-C
Server Side Swift
PPT.pptxvkjvwbjbbikvhixhkiheihhiiihwxhhi
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
What’s new in Swift 5.2-5.3
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th E...
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
To Protect & To Serve
iphone application development
What Makes Objective C Dynamic?
Swift
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift for-rubyists
Open Source Swift Under the Hood
Swift, a quick overview
Ad

Recently uploaded (20)

PDF
System and Network Administration Chapter 2
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by AndrƩ Kraus
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
top salesforce developer skills in 2025.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Transform Your Business with a Software ERP System
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
System and Network Administraation Chapter 3
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
System and Network Administration Chapter 2
PTS Company Brochure 2025 (1).pdf.......
T3DD25 TYPO3 Content Blocks - Deep Dive by AndrƩ Kraus
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
top salesforce developer skills in 2025.pdf
Operating system designcfffgfgggggggvggggggggg
Transform Your Business with a Software ERP System
wealthsignaloriginal-com-DS-text-... (1).pdf
How Creative Agencies Leverage Project Management Software.pdf
ai tools demonstartion for schools and inter college
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Navsoft: AI-Powered Business Solutions & Custom Software Development
System and Network Administraation Chapter 3
Which alternative to Crystal Reports is best for small or large businesses.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Adobe Illustrator 28.6 Crack My Vision of Vector Design

CocoaConf DC - Automate with Swift - Tony Ingraldi

  • 1. Automate with Swift CocoaConf DC, April 10, 2015 Tony Ingraldi GitHub: tingraldi • Twitter: @TonyIngraldi
  • 2. Itinerary • Motivation: Why Automate? • A bit of history • Why Swift? • Nuts and bolts
  • 3. Show of Hands? • Have you used… • AppleScript? • Automator? • Other form of application scripting?
  • 4. Why Automate? • Improve productivity • Avoid repetitive tasks • Streamline workflows • Opportunities for experimentation • Add missing features to OS X apps!
  • 7. Open Scripting Architecture • Introduced way back in October 1993 • The state of the Mac looked like this Beige!
  • 8. Open Scripting Architecture • Survived the transition to OS X • Leveraged by OS X to launch applications, open documents, etc. • A standard mechanism for interapplication communication
  • 9. Language Options • AppleScript (there from the beginning) • JavaScript for Automation (as of Yosemite) • Python (PyObjC, py-appscript) • Ruby (RubyCocoa, RubyOSA) • And now Swift!
  • 10. Language Options • AppleScript (there from the beginning) • JavaScript for Automation (as of Yosemite) • Python (PyObjC, py-appscript) • Ruby (RubyCocoa, RubyOSA) • And now Swift!
  • 11. AppleScript • A ā€œnatural languageā€ programming model • Primarily geared toward being the ā€œglueā€ between apps • Limited inherent functionality
  • 12. AppleScript • Can be frustrating to people who are fluent in ā€œnormalā€ programming languages • Verbosity is a hallmark set fileName to "name.jpg" set sansExtension to text 1 thru ((offset of "." in fileName) - 1) of fileName
  • 13. Swift • A ā€œprimaryā€ language • Ready access to Cocoa • Can run Swift scripts using #! convention • A familiar coding style let fileName = "name.jpg" let sansExtension = fileName.stringByDeletingPathExtension
  • 14. Scripting Bridge • Introduced in Mac OS X Leopard (version 10.5) • Provides high-level Objective-C access to scriptable applications • Can be leveraged in Swift, with a bit of extra work
  • 15. Scripting Bridge Recipe • 1 part sdef • 1 part sdp • A pinch of manual intervention • Automate to taste
  • 16. Scripting Definition • Scriptable applications include resources that describe their scripting interface • Can be in a variety of forms • The sdef command-line utility extracts the scripting definition • Writes to standard output in XML format
  • 17. Scripting Definition • Using sdef sdef /path/to/App.app > App.sdef • For the most part, using sdef is ā€œrun and forgetā€ • Until you find out what’s wrong when you run sdp • Some sdp warnings can be ignored
  • 18. Scripting Definition • Using sdp sdp -fh --basename App App.sdef
  • 20. Kicking the Tires • Xcode • Swift and ObjC command line targets • Includes the header generated by sdp • Experiment in main.swift and main.m
  • 22. Don’t Run with Scissors • Using Objective-C header leads to pervasive AnyObject typing • Works, but can lead to ambiguity • For properties, sometimes have to resort to using valueForKey • Sometimes leads to awkward method invocation
  • 23. An Alternative • Create Swift protocols that cover the generated Objective-C API • šŸ‘ Supports rich set of types • šŸ‘ API translation can be automated • šŸ‘Ž Requires optional declaration of all properties and methods
  • 24. Objective-C Excerpt @interface AcornApplication : SBApplication @property (copy, readonly) NSString *name; - (SBElementArray *) windows; - (NSString *) taunt; @end
  • 25. SBObject @objc public protocol SBObjectProtocol: NSObjectProtocol { func get() -> AnyObject! }
  • 26. SBApplication @objc public protocol SBApplicationProtocol: SBObjectProtocol { func activate() var delegate:SBApplicationDelegate! { get set } }
  • 27. Application Protocol @objc public protocol AcornApplication: SBApplicationProtocol { optional var name: String { get } optional func windows() -> SBElementArray optional func taunt() -> String } extension SBApplication : AcornApplication {}
  • 28. Putting it Together import ScriptingBridge @objc public protocol AcornApplication : … {…} extension SBApplication : AcornApplication {} let acorn = SBApplication .applicationWithBundleIdentifier( ā€œcom.flyingmeat.Acorn4" ) as! AcornApplication acorn.taunt!()
  • 30. Plan of Attack • Create frameworks for target applications • Install in /Library/Frameworks • Write scripts instead of compiled code
  • 31. By the Way • Playgrounds don’t fit well • The Swift REPL could spontaneously combust at any moment • What’s a scripter to do? • Use a text editor • Edit, run, repeat
  • 32. Script Invocation • Hash-bang on the first line #!/usr/bin/xcrun swift -F /Library/Frameworks • chmod +x SomeScript.swift
  • 33. A Little Help https://github.com/tingraldi/SwiftScripting • Header conversion utilities • Sample Application Scripting Frameworks • Sample Scripts • Scripting Utilities Framework
  • 35. A Little More Help import ScriptingBridge @objc public protocol AcornApplication {…} extension SBApplication : AcornApplication {} let acorn = SBApplication .applicationWithBundleIdentifier( "com.flyingmeat.Acorn4" ) as! AcornApplication acorn.taunt!()
  • 36. A Little More Help import ScriptingBridge import AcornScripting // Acorn Swift protocols let acorn = SBApplication .applicationWithBundleIdentifier( "com.flyingmeat.Acorn4" ) as! AcornApplication acorn.taunt!()
  • 37. A Little More Help import ScriptingUtilities // Helper framework import AcornScripting // Acorn Swift protocols let acorn = Application(name: "Acorn") as! AcornApplication acorn.taunt!()
  • 38. Where to Put Scripts? • Short answer: anywhere • Some applications have special script folders • Scripting Menu • Invoke via an Automator Service
  • 40. Summary • Automate for productivity • Add ā€œmissing featuresā€ • Reinforce/leverage Swift expertise