Search code examples
macosswiftapplescriptitunes-sdk

Applescript to Swift Language (application control)


I wasn't sure what to call the title, but I'm working on an Applescript that pulls/pushes information from iTunes and save it. During the development of my Applescript I figured that if I'm going to learn a language, I'm going learn Swift as I want to develop more advanced programs down the road. Even though Applescript is as useful, and what I'm doing is working in Applescript... I wanted to take the next step in Learning to develop programs and scripts using Swift. I want to be able to replicate what I was able to do in Applescript using Swift.

What I wanted to know is if there is a tutorial/guide on how to read data from the accessibility inspector/etc and control programs like applescript is capable of doing, etc...

To give you a background on what I was able to do in Applescript, it's a really basic version of Batch Apple ID Creator. I work for a small school district that is now using a MDM to manage the i-devices. Well, with the MDM, each device needs to have it's own apple ID and manually creating 500+ apple ID is not as much fun as it sounds. These are some one the steps that I recreated in Applescript.

  • Check to see if iTunes is running
  • Check to see if there is a current user logged in.
  • Click "Sign Out" under menu bar if current user is logged in.
  • Goto "Create Apple ID..."
  • etc.

I took the current script that is up on that Git repo and made some changes to it so it works with the latest version of iTunes (12.1.2). After making some changes, I figures I wanted to learn and started rewriting the script to fully understand how it works and to learn Applescript syntax.

Let me know if you need more information about what I'm trying to do.

Throdne


Solution

  • I am investigating this sort of thing myself. What amazes me is that you can use Swift as a scripting language. I've written several short scripts that use the simple 'shebang' line #!/usr/bin/swift

    To access AppleScript functionality you almost have to call AppleScript (through Cocoa) from your Swift code.

    Here's an example I found elsewhere:

    Swift Code

    let myAppleScript = "..."
    var error: NSDictionary?
    if let scriptObject = NSAppleScript(source: myAppleScript) {
        if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(
                                                                           &error) {
            println(output.stringValue)
        } else if (error != nil) {
            println("error: \(error)")
        }
    }
    

    try searching for 'call AppleScript from Swift' (or Cocoa) or 'call AppleEvents from Swift' (or Cocoa).