Build an Application to Run a Shell Command in Xcode and Swift – Part 1

This is a simple task but a nice project to find your way around Xcode and Swift. We will build a small Cocoa application in Xcode that executes a shell command on the click of a button.

Note: I have a new post on this topic, updated for Swift 5.1 and SwiftUI.

For this example we will use the say command which use OS X’s text to speech to say a given text. You can try this by opening the Terminal and typing say "Hello world".

This tutorial is for Xcode 7.3 with OS X 10.11.4 El Capitan. It will probably not change too much with minor version changes, but no promises for major version differences.

All you need is a Mac with 10.11.4+ El Capitan and Xcode 7.3+ which you can download for free in the Mac App Store or Apple’s Developer page (free registration with any Apple ID required).

Creating the Project

Once you have downloaded and installed Xcode, launch it. It may prompt you for some extra installations and a password on first launch. Acknowledge those and you get to a splash screen with a few options. If you have used Xcode before it will list your previous projects. But for now, select “Create a new Xcode Project”.

1-SplashScreen

On the next step Xcode suggests many templates to build your application from. Select “Application” under “OS X” and then the “Cocoa Application” icon. Then click next to continue.

2-ChooseTemplate

In the next step you will have to fill in some identification for your applications. For the “ProductName” or the name of the application enter “SayThis”. Fill your name or organization name into the next field. The identifier in the third field should follow a “reverse DNS schema” for your organization. It is ok to use more than two segments, like “com.example.department”. If you don’t really know what to put in here use your email or github account in reverse order, i.e. “com.gmail.username” or “com.github.username”.

For the language select Swift and disable “Use Storyboards” and every other checkbox here. Our first application is going to be very simple.

3-ProjectOptions

Finally, Xcode will ask you where to save the project. Xcode will create a folder named “SayThis” with all the necessary files. If you want, you can make the project folder a local git repository for version control.

Creating the Interface

The Xcode window has a navigation area or file selector on the left, a main editor area in the center and an utility or information panel on the right. There are buttons in top right toolbar to show and hide the left and right panels.

4-PanelButtons

Right now the project itself is selected in the navigation area and the center editor shows various properties of the project. These were already set to useful defaults when the template was setup.

There are four files in this particular template. Select “MainMenu.xib”. xib files store how the interface looks like. The editor will change to a graphical area to design the interface. The application’s menu bar is at the top. However, there is no window to put an interface visible. There is a list of icons, next to the navigation bar, representing various objects in this xib file. The lowest is a window.

5-Objects

Click the icon to make the window visible in the editor area.

6-Window

In the lower right corner of the Xcode window is a list of objects that can be added to the interface. You may have to select the circle icon with a square in it to see it. You can scroll through the list, but there are so many objects that it is easier to use the search field at the very bottom.

7-ObjectPalette

Enter ‘button’ in the search then drag the “Push Button” to your window. As you drag the button around the window, you will see blue lines appear, guiding the button to the right center line or the right distance from the edges of the window. Use the blue guide lines to drop the button in the center of the window.

8-FirstButton

You can double-click the text on the button to change the default label. Let’s use “Talk”. At this time you can already “Build and Run” the project. There is a “Play” triangle button in the upper right area of the window or you can choose “Run” from the project menu. Since this is the first time to build this project it will take a bit longer.
Xcode will launch the application after building and it should show the window with the “Talk” button. You can click the button, however aside from the standard click animation, nothing will happen, since we haven’t told the button to do anything yet.

To connect the button to some action, we need to connect it to some code. We need to show the code and the UI side-by-side. There is a toolbar button on the right with two blue circles, click that and choose “Assistant Editors on Bottom” or “…on Right” (your choice) to open a second editor pane.

9-AssistantEditor

By default Xcode will show a header file we do not care about in the second panel. You can change this by clicking in the title bar of the second pane and selecting “Manual > SayThis > SayThis > AppDelegate.swift”

10-selectAppController

11-AssistantEditorWindow

The template filled the AppDelegate.swift file with some code and one property that is connected to the window. We want perform an action method in the AppDelegate when the button it clicked. To make this connection hold the ctrl-key and drag from the button to the empty space in the AppDelegate below the two template function, but above the final closing brace }. When you end the drag there a small dialog will pop up asking for specific settings. Set it to be an action, name it talk and set the sender type to NSButton.

ConnectTalkButton

This inserts an empty action method into the AppDelegate class.

    @IBAction func talk(sender: NSButton) {
    }

The @IBAction is a label for the interface builder part of Xcode to know this function is available to connect to the UI. func designates this as a function, but since this is within the definition of the AppDelegate class it is actually a class method of AppDelegate. In the brackets we define one parameter, labelled sender of type NSButton. The curly braces enclose the function code which is still empty.

Insert the following code between the curly braces:

    @IBAction func talk(sender: NSButton) {
        let path = "/usr/bin/say"
        let arguments = ["hello world"]
        
        let task = NSTask.launchedTaskWithLaunchPath(path, arguments: arguments)
        task.waitUntilExit()
    }

While you are typing Xcode will suggest completions for the code that you are typing. This can be very helpful and helps you avoid typing errors. You can hit the tab-key to accept the suggestion.

13-CodeCompletion

The let statement is very particular to Swift and declares a variable as constant. The alternative label var would tell the compiler that we plan to change the content of the variable later. Choosing let and var properly will allow the compiler to optimize the resulting code. For example in this specific case, the compiler will use a non-mutable string and array class for our arguments, since they will not change later in the code.

If you replace let with var and build then the compiler will notice you are not modifying the variable and place a warning that you should use let instead.

14-letwarning

Since the say command will not run within a shell and we cannot rely on environment variables being set, especially the PATH variable, we need to give the full path to the say command. To figure out the full path to a command you can use the which command in Terminal.

$ which say
/usr/bin/say

The arguments are passed as an array of Strings. Right now we have only a single static argument, but we could pass more, each option or argument will be its own String in the array. so if you wanted to use another voice you could extend the array to

let arguments = ["hello world", "-v", "Kathy"]

(One String per argument, no need to escape spaces.)

Finally we use the NSTask class to create and launch the command. Then the waitUntilExit() method of NSTask pauses code execution until the command finished.

There is a minor problem in the UI. If you hit the button quickly in succession, you will get multiple “hello worlds” on top of each other. One solution to that is to disable the button while the task is being processed. Alle interface elements have an enabled property we can use for that purpose. Change the talk method to this:

    @IBAction func talk(sender: NSButton) {
        let path = "/usr/bin/say"
        let arguments = ["hello world"]
        
        sender.enabled = false
        
        let task = NSTask.launchedTaskWithLaunchPath(path, arguments: arguments)
        task.waitUntilExit()
        
        sender.enabled = true
    }

Before we execute the task, we disable the button, then enable it later. Now, when you click the button it will be disabled while the task is running and be re-enabled afterwards.

Congratulations! You have built a simple OS X Application. In the next part, we will hook up a few more UI Elements to give the app some more functionality.

Continue to Part 2

Randomize Window Backgrounds in Terminal

Quick Terminal tip:

Make a copy of the /Library/Desktop Pictures/Solid Colors/ directory in your home folder and delete all dark and medium gray color files from the copy.

In “Terminal” > “Preferences” > “Profiles” choose the “Basic” profile. Drag your copy of the Solid Colors folder from the Finder on to area next to the “Image” label where it says “no Background Image”.

TerminalProfile

If you already have Terminal windows using this profile they should apply the color immediately, and any other terminal window you open will get a random background from the colors in your folder.

ColoredTerminals

If you prefer light text on dark background you can remove the lighter colors from the folder instead, or make your own set of background images. Enjoy!

AutoPkg Recipe definition for PlistEdit Pro

With AutoPkg and Munki you are juggling property list files all the time. Sometimes using a text editor is the best choice, other times you want a graphical representation of the property list. Xcode can be used for that, but launching Xcode for a humble plist always seems overkill… and slow. My preferred tool of choice for this is FatCat Software’s PlistEdit Pro.

AutoPkg recipes have a well defined format. Creating them from scratch in an editor can be boring and error prone. PlistEdit Pro offers a feature called ‘Structure definitions’ which… well… allows you to define the structure of a property list. Best thing is you can create your own, though the documentation on their website is a bit outdated.

If you want to do this, download this definition file and put it in ~/Library/Application Support/PlistEdit Pro/Structure Definitions. Then restart PlistEdit Pro. Finally, go to “Preferences > Definitions”, select the “AutoPkg Recipe” in the list and add ‘recipe’ as a file extension.

Now when you open a .recipe file, it will know to use this definition. This will help with some steps of managing recipes. For example when you create a new element in the Process array, it will automatically be set to be a dict and pre-filled with a Processor string element and a Arguments array element. It will also warn when you try to delete mandatory elements.

When you create a new empty file and change the definition from the ‘Definition’ menu, it will pre-fill your new file with the right keys for a recipe. Enjoy!

Make tab-completion in bash case-insensitive

I added this to a discussion on the MacAdmins Slack today and realized it could be useful for a broader audience.

The underlying problem is that by default HFS+ (the file system of OS X) is “case preserving, but case-insensitive.” That means the file system will remember wether you named a file or directory “README.TXT” “ReadMe.txt” or “readme.TXT” and preserve that case, but using either of these will point to the same file.

This may be confusing in Terminal. Since most other Unix and Linux file-system are case-sensitive (i.e. README.TXT and readme.txt are different files) most shells are, too. So on OS X in bash you can write:

$ cd ~/DESKTOP

and it will actually work. Though if you then print the working directory, you get

$ pwd
/Users/armin/DESKTOP

which doesn’t hurt anything really, since Desktop and DESKTOP are the same. But it does hurt our OCD, right?

While I have not yet found a way to change this behaviour directly, one thing you can change is wether tab-completion is case-sensitive or not. Since the underlying filesystem is insensitive, there really is no reason tab-completion should be. This way you can type /sy[tab]/l[tab]/cor[tab] and it will expand to /System/Library/CoreServices/.

Tab-completion is not just for laziness, but also a way to ensure you are typing a path correctly, especially since tab-completion will escape spaces and other nasty characters automatically.

To make tab-completion in bash case-insensitive put this in your .inputrc (create if necessary)

# Ignore case while completing
set completion-ignore-case on

and then close all Terminal windows and start a new one.

quickpkg update

I updated quickpkg with a few additions:

Scripts

You can now add pre- and postinstall scripts or an entire folder of scripts.

Ownership

Added an --ownership parameter that will be passed straight through to pkgbuild. Usually the default recommended will be what you want, but it is there if you need it.

Output

There is now a --output parameter that gives you more control over the location and name of the resulting package.

Bonus Trick

And as a neat trick, you can easily create a droplet for quickpkg with Automator by following the same instructions as for munkiimport in this article.