Screen Shot 2014-11-04 at 12.26.52By Paris Buttfield-Addison, Jonathon Manning & Tim Nugent

The following is an extract from “Swift Development with Cocoa: Developing for the Mac and iOS App Stores”, published by OReilly.




Let’s jump right into working with Xcode. We’ll begin by creating a simple iOS application and then connect it together. If you’re more interested in Mac development, don’t worry—the same techniques apply.

This sample application will display a single button that, when tapped, will pop up an alert and change the button’s label to Test!. We’re going to build on the project we created earlier, so make sure that you have that project open.

It’s generally a good practice to design the interface first and then add code. This means that your code is written with an understanding of how it maps to what the user sees.

To that end, we’ll start by designing the interface for the application.

Designing the Interface

When building an application’s interface using Cocoa and CocoaTouch, you have two options. You can either design your application’s screens in a storyboard, which shows how all the screens link together, or you can design each screen in isolation. This book covers storyboards in more detail later; for now, this first application has only one screen, so it doesn’t matter much either way.

Start by opening the interface file and adding a button:

1. Open the main storyboard. Because newly created projects use storyboards by default, your app’s interface is stored in the file Main.storyboard.

Open it by selecting it in the project navigator. The editor will change to show the application’s single, blank screen.

2. Drag in a button. We’re going to add a single button to the screen. All user interface controls are kept in the object library, which is at the bottom of the Details pane on the righthand side of the screen.

To find the button, you can either scroll through the list until you find Button, or type button in the search field at the bottom of the library.

Once you’ve located it, drag it into the screen.

3. Configure the button. Every item that you add to an interface can be configured. For now, we’ll only change the label.

Select the new button by clicking it, and select the Attributes inspector , which is the third tab from the right at the top of the Utilities pane. You can also reach it by pressing ⌘-Option-4.

Change the button’s Title to Hello!

You can also change the button’s title by double-clicking it in the interface.

Our simple interface is now complete (Figure 1-9). The only thing left is to connect it to code.

Screen Shot 2014-11-04 at 12.44.42

Figure 1-9. Our completed simple interface.

Connecting the Code

Applications aren’t just interfaces—as a developer, you also need to write code. To work with the interface you’ve designed, you need to create connections between your code and your interface.

There are two kinds of connections that you can make:

Outlets are variables that refer to objects in the interface. Using outlets, you can instruct a button to change color or size, or hide itself. There are also outlet collec‐ tions, which allow you to create an array of outlets and choose which objects it contains in the Interface Builder.

Actions are methods in your code that are run in response to the user interacting with an object. These interactions include the user touching a finger to an object, dragging a finger, and so on.

To make the application behave as we’ve described above—tapping the button displays a label and changes the button’s text—we’ll need to use both an outlet and an action. The action will run when the button is tapped, and will use the outlet connection to the button to modify its label.

To create actions and outlets, you need to have both the interface editor and its corre‐ sponding code open. Then hold down the Control key and drag from an object in the interface editor to your code (or to another object in the interface editor, if you want to graphical user interfaces make a connection between two objects in your interface).

We’ll now create the necessary connections:

1. Open the assistant. To do this, select the second tab in the editor selector in the toolbar.

The assistant should show the corresponding code for interface View Controller.swift. If it doesn’t, click the interwining circles icon (which represents the assistant) and navigate to Automatic→ViewController.swift.

2. Create the button’s outlet. Hold down the Control key and drag from the button into the space below the first { in the code.

A pop-up window will appear. Leave everything as the default, but change the Name to helloButton. Click Connect.

A new line of code will appear: Xcode has created the connection for you, which appears in your code as a property in your class.

3. Create the button’s action. Hold down the Control key, and again drag from the button into the space below the line of code we just created. A pop-up window will again appear.

This time, change the Connection from Outlet to Action. Set the Name to showA lert. Click Connect.

A second new line of code will appear. Xcode has created the connection, which is a method inside the ViewController class.

4. In the showAlert method. you just added, add in the new code:

@IBAction func showAlert(sender: AnyObject) {
    var alert = UIAlertController(title: "Hello!", message: "Hello, world!", preferredStyle: UIA
    alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: ni
    self.presentViewController(alert, animated: true, completion: nil)
    self.helloButton.setTitle("Clicked", forState: UIControlState.Normal)

This code creates a UIAlertController, which displays a message to the user in a pop- up window. It prepares it by setting its title to “Hello! and the text inside the window to “Hello, world!” The alert is then shown to the user. Finally, an action (doing nothing but dismissing the alert in this case) is added with the text “Click”. It then sets the title of the button to “Clicked”.
The application is now ready to run. Click the Run button at the top-left corner. The application will launch in the iPhone simulator.

If you happen to have an iPhone or iPad connected to your comput‐ er, Xcode will by default try to launch the application on the device rather than in the simulator. To make Xcode use the simulator, go to the Scheme menu at the top-left corner of the window and change the currently selected scheme to the simulator.

When the app finishes launching in the simulator, tap the button. An alert will appear; when you close it, you’ll notice that the button’s text has changed.

Using the iOS Simulator

The iOS Simulator (Figure 1-10) allows you to test out iOS applications without having to mess around with devices. It’s a useful tool, but keep in mind that the simulator and a real device behave very differently.

Screen Shot 2014-11-04 at 12.43.25Figure 1-10. The iOS Simulator

For one thing, the simulator is a lot faster than a real device and has a lot more memory. That’s because the simulator makes use of your computer’s resources—if your Mac has 8GB of RAM, so will the simulator, and if you’re building a processor-intensive appli‐ cation, it will run much more smoothly on the simulator than on a real device.

The iOS Simulator is able to simulate many different kinds of devices: everything from the iPad 2, to the latest iPads, and from the retina-display 3.5 inch iPhone-sized devices, to the retina-display 4 inch iPhone-sized devices, to the latest 4.7 inch and 5.5 inch iPhones.

To change the device, open the Hardware menu, choose Device, and select the device you want to simulate. You can also change which simulator to use via the Scheme selector in Xcode.

You can also simulate hardware events, such as the home button being pressed or the iPhone being locked. To simulate pressing the home button, you can either click the virtual button underneath the screen, choose Hardware→Home, or press ⌘-Shift-H. To lock the device, press ⌘-L or choose Hardware→Lock.

If there’s no room on the screen, the simulator won’t show the virtu‐ al hardware buttons. So if you want to simulate the home button being pressed, you need to use the keyboard shortcut ⌘-Shift-H.

There are a number of additional features in the simulator, which we’ll examine more closely as they become relevant to the various parts of iOS we’ll be discussing.

Testing iOS Apps with TestFlight

TestFlight is a service operated by Apple that allows you to send copies of your app to people for testing. Using TestFlight, you can send builds of your app to both people in your organization, as well as to up to a thousand external testers.

TestFlight allows you to submit testing builds to up to 25 people who are members of your Developer Program account. Additionally, you can send the app to up to a thousand additional people for testing, once the app is given a preliminary review by Apple.

To use TestFlight, you configure the application in iTunes Connect by providing infor‐ mation like the app’s name, icon, and description. You also create a list of users who should receive the application. You then upload a build of the app through Xcode, and Apple emails them a link to download and test it.

For more information on how to use TestFlight, see the iTunes Connect documentation:



Developing a Simple Swift Application

About The Author

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>