I want to get you started right away with a feel for what this is all about and to motivate your continued progress toward being a great developer, so let’s get to it and do something with your iPhone (see Figure 2-1). In this chapter, using Xcode, let’s create a small iOS application that will display “Hello, World!” on the screen. You’ll look at what’s involved in creating the project in Xcode , work through the specifics of using Xcode’s Interface Builder to design your application’s user interface, and then execute your application on the iOS simulator and an actual device. You’ll finish up by giving your application an icon to make it feel more like a real iOS application.
Figure 2-1. The results of the app you create in this chapter might seem simple, but your work will start you down the road to potential iOS greatness
Creating the Hello World Project
By now, you should have installed Xcode 9 and the iOS SDK onto your Mac. You can also download the book’s source code archive from the Apress web site ( www.apress.com ). While you’re at it, take a look at the book forums at http://forum.learncocoa.org . The book forums are a great place to discuss iOS development, get your questions answered, and meet up with like-minded people.
Note
Even though you have the complete set of project files at your disposal in this book’s source code archive, you’ll get more out of the book if you create each project by hand, rather than simply running the version you downloaded. By doing that, you’ll gain familiarity and expertise working with the various application development tools.
The project you’re going to build in this chapter is contained in the Hello World folder of the source code archive.
Before you can start, you need to launch Xcode, the tool you’ll be using to do most of what you do in this book. After downloading it from the Mac App Store or the Apple Developer site, you’ll find it installed in the /Applications folder, as with most Mac applications. You’ll be using Xcode a lot, so you might want to consider dragging it to your dock so you’ll have ready access to it.
If this is your first time using Xcode, don’t worry; I’ll walk you through every step involved in creating a new project. If you’re already an old hand but haven’t worked with Xcode 7, you may find that some things have changed (mostly for the better, I think).
When you first launch Xcode , you’ll be presented with a welcome window like the one shown in Figure 2-2. From here, you can choose to create a new project, connect to a version control system to check out an existing project, or select from a list of recently opened projects. The welcome window gives you a nice starting point, covering some of the most common tasks you might do after starting Xcode. All of these actions can be accessed through the menu as well, so close the window to proceed. If you would rather not see this window in the future, just deselect the “Show this window when Xcode launches” check box at the bottom of the window before closing it.
Figure 2-2. The Xcode welcome window
Create a new project by selecting New ➤ Project from the File menu (or by pressing ⌘⇧N). A new project window will open, showing you the project template selection sheet (see Figure 2-3). From this sheet, you’ll choose a project template to use as a starting point for building your application. The bar at the top is divided into five sections: iOS, watchOS, tvOS, macOS, and Cross-platform. Since you’re building an iOS application, select the iOS button to reveal the application templates.
Figure 2-3. The project template selection sheet lets you select from various templates when creating a new project
Each of the icons shown in the upper-right pane in Figure 2-3 represents a separate project template that can be used as a starting point for your iOS applications. The icon labeled Single View App contains the simplest template and the one you’ll be using for the first several chapters. The other templates provide additional code and/or resources needed to create common iPhone and iPad application interfaces, as you’ll see in later chapters.
Click the Single View App (see Figure 2-3) and then click the Next button. You’ll see the project options sheet, which should look like Figure 2-4. On this sheet, you need to specify the product name and company identifier for your project. Xcode will combine these to generate a unique bundle identifier for your app. You’ll also see a field that lets you enter an organization name, which Xcode will use to automatically insert a copyright notice into every source code file you create. Name your product Hello World and enter an organization name and identifier in the Organization Name and Organization Identifier fields, as shown in Figure 2-4. Don’t use the same name and identifier as the ones shown in Figure 2-4. For reasons that you’ll see when you try to run this application on a real device at the end of the chapter, you’ll need to choose an identifier that’s unique to you (or your company).
Figure 2-4. Selecting a product name and organization identifier for your project
The Language field lets you select the programming language you want to use, choosing between Objective-C and Swift, but since all the examples in the book are in Swift, the appropriate choice here is, of course, Swift.
You also need to specify the devices. In other words, Xcode wants to know if you’re building an app for the iPhone and iPod touch, if you’re building an app for the iPad, or if you’re building a universal application that will run on all iOS devices. Select iPhone in the Devices drop-down menu if it’s not already selected. This tells Xcode that you’ll be targeting this particular app at the iPhone. For the first few chapters of the book, you’ll be using the iPhone device, but don’t worry—I’ll cover the iPad also.
Leave the Core Data check box unselected—you’ll make use of it later. You can also leave the Include Unit Tests and Include UI Tests check boxes unselected. Xcode has good support for testing your applications, but that’s outside the scope of this book, so you don’t need Xcode to include support for them in your project. Click Next again and you’ll be asked where to save your new project using a standard save sheet (see Figure 2-5). If you haven’t already done so, use the New Folder button to create a new master directory for these book projects and then return to Xcode and navigate into that directory. Before you click the Create button, take note of the Source Control check box. Git isn’t covered in this book, but Xcode includes some support for using Git and other kinds of source control management (SCM) tools . If you are already familiar with Git and want to use it, select this check box; otherwise, feel free to turn it off.
Figure 2-5. Saving your project in a project folder on your hard drive
Taking a Look at the Xcode Project Window
After you dismiss the save sheet, Xcode will create and then open your project. You will see a new project window, as shown in Figure 2-6. There’s a lot of information in this window; it’s where you’ll spend a lot of iOS development time.
Figure 2-6. The Hello World project in Xcode
The Toolbar
The top of the Xcode project window is called the toolbar (see Figure 2-7). On the left side of the toolbar you’ll see controls to start and stop running your project, as well as a pop-up menu to select the scheme you want to run. A scheme brings together target and build settings, and the toolbar pop-up menus let you select a specific setup quickly and easily.
Figure 2-7. The Xcode toolbar
The big box in the middle of the toolbar is the activity view. As its name implies, the activity view displays any actions or processes that are currently happening. For example, when you run your project, the activity view gives you a running commentary on the various steps it’s taking to build your application. If you encounter any errors or warnings, that information is displayed here, as well. If you click the warning or error, you’ll go directly to the Issue Navigator, which provides more information about the warning or error, as described in the next section.
On the right side of the toolbar are two sets of buttons. The left set lets you switch between three different editor configurations.
Editor Area: The Editor Area gives you a single pane dedicated to editing a file or project-specific configuration values.
Assistant Editor: The powerful Assistant Editor splits the Editor Area into multiple panes, left, right, top, and bottom. The pane on the right is generally used to display a file that relates to the file on the left or that you might need to refer to while editing the file on the left. You can manually specify what goes into each pane, or you can let Xcode decide what’s most appropriate for the task at hand. For example, if you’re designing your user interface on the left, Xcode will show you the code that the user interface is able to interact with on the right. You’ll see the Assistant Editor at work throughout the book.
Comparison view: The Version Editor button converts the editor pane into a time machine–like comparison view that works with version control systems like Git. You can compare the current version of a source file with a previously committed version or compare any two earlier versions with each other.
To the right of the editor buttons is a set of toggle buttons that show and hide large panes on the left and right sides of the editor pane, as well as the debug area at the bottom of the window . Click each of those buttons a few times to see these panes in action. You’ll explore how these are used soon.
The Navigator
Just below the toolbar on the left side of the project window is called the navigator. The navigator offers eight views that show you different aspects of your project. Click each of the icons at the top of the navigator to switch among the following navigators, going from left to right:
Project Navigator: This view contains a list of files in your project, as shown in Figure 2-8. You can store references to everything you expect—from source code files to artwork, data models, property list (or .plist) files (discussed in the “Taking a Closer Look at the Hello World Project” section later in this chapter), and even other project files. By storing multiple projects in a single workspace, those projects can easily share resources. If you click any file in the navigator view, that file will display in the Editor Area. In addition to viewing the file, you can edit it, if it’s a file that Xcode knows how to edit.
Figure 2-8. The Xcode Project Navigator. Click one of the eight icons at the top of the view to switch navigators.
Symbol Navigator: As its name implies, this navigator focuses on the symbols defined in the workspace (see Figure 2-9). Symbols are basically the items that the compiler recognizes, such as classes, enumerations, structs, and global variables.
Figure 2-9. The Xcode Symbol Navigator. Open the disclosure triangle to explore the classes, methods, and other symbols defined within each group.
Find Navigator: You’ll use this navigator to perform searches on all the files in your workspace (see Figure 2-10). At the top of this pane is a multileveled pop-up control letting you select Replace instead of Find, along with other options for applying search criteria to the text you enter. Below the text field, other controls let you choose to search in the entire project or just a portion of it and specify whether searching should be case-sensitive.
Figure 2-10. The Xcode Find Navigator. Be sure to check out the pop-up menus hidden under the word Find and under the buttons that are below the search field.
Issue Navigator: When you build your project , any errors or warnings will appear in this navigator, and a message detailing the number of errors will appear in the activity view at the top of the window (see Figure 2-11). When you click an error in the Issue Navigator, you’ll jump to the appropriate line of code in the editor.
Figure 2-11. The Xcode Issue Navigator. This is where you’ll find your compiler errors and warnings.
Test Navigator: If you’re using Xcode’s integrated unit testing capabilities (a topic that isn’t covered in this book), this is where you’ll see the results of your unit tests. Since you didn’t include unit tests in the example project, this navigator is empty (see Figure 2-12).
Figure 2-12. The Xcode Test Navigator. The output of your unit tests will appear here.
Debug Navigator: This navigator provides your main view into the debugging process (see Figure 2-13). If you are new to debugging, you might check out this part of the Xcode Overview: https://developer.apple.com/support/debugging/ . The Debug Navigator lists the stack frame for each active thread. A stack frame is a list of the functions or methods that have been called previously, in the order they were called. Click a method, and the associated code appears in the editor pane. In the editor, there will be a second pane that lets you control the debugging process, display and modify data values, and access the low-level debugger. A button at the bottom of the Debug Navigator allows you to control which stack frames are visible. Another button lets you choose whether to show all threads or just the threads that have crashed or stopped on a breakpoint. Hover your mouse over each of these buttons in turn to see which is which.
Figure 2-13. The Xcode Debug Navigator. Controls at the bottom of the navigator let you control the level of detail you want to see.
Breakpoint Navigator: The Breakpoint Navigator lets you see all the breakpoints that you’ve set, as shown in Figure 2-14. Breakpoints are, as the name suggests, points in your code where the application will stop running (or break) so that you can look at the values in variables and do other tasks needed to debug your application. The list of breakpoints in this navigator is organized by file. Click a breakpoint in the list and that line will appear in the editor pane. Be sure to check out the plus sign (+) button at the lower-left corner of the project window when in the Breakpoint Navigator. This button opens a pop-up that lets you add four different types of breakpoints, including symbolic breakpoints, which are the ones you will use most often.
Figure 2-14. The Xcode Breakpoint Navigator. The list of breakpoints is organized by file.
Report Navigator: This navigator keeps a history of your recent build results and run logs, as shown in Figure 2-15. Click a specific log, and the build command and any build issues are displayed in the edit pane.
Figure 2-15. The Xcode Report Navigator . The Report Navigator displays a list of builds, with the details associated with a selected view displayed in the editor pane.
The Jump Bar
Across the top of the editor, you’ll find a control called the jump bar. With a single click, the jump bar allows you to jump to a specific element in the hierarchy you are currently navigating. For example, Figure 2-16 shows a source file being edited in the editor pane.
Figure 2-16. The Xcode editor pane showing the jump bar, with a source code file selected. The submenu shows the list of methods in the selected file .
The jump bar sits just above the source code. Here’s how it breaks down:
The funky-looking icon at the left end of the jump bar is actually a pop-up menu that displays submenus listing recent files, counterparts, superclasses and subclasses, siblings, categories, includes, and more. The submenus shown here will take you to just about any other code that touches the code currently open in the editor .
To the right of the menu are left and right arrows that take you back to the previous file and return you to the next file, respectively.
The jump bar includes a segmented pop-up that displays the hierarchical path to reach the selected file in the project. You can click any segment showing the name of a group or a file to see all the other files and groups located at the same point in the hierarchy. The final segment shows a list of items within the selected file. In Figure 2-16, you see that the tail end of the jump bar is a pop-up that shows the methods and other symbols contained within the currently selected file. The jump bar shows the AppDelegate.swift file with a submenu listing the symbols defined in that file.
Look for the jump bar as you make your way through the various interface elements of Xcode.
Tip
Like most of Apple’s macOS applications, Xcode includes full support for full-screen mode. Just click the full-screen button in the upper right of the project window to try out distraction-free, full-screen coding!
The Utilities Area
As mentioned earlier, the second-to-last button on the right side of the Xcode toolbar opens and closes the Utilities area. The upper part of the utilities area is a context-sensitive inspector panel, with contents that change depending on what is being displayed in the editor pane. The lower part of the Utilities area contains a few different kinds of resources that you can drag into your project. You’ll see examples of this throughout the book.
Interface Builder
Earlier versions of Xcode included a separate interface design application called Interface Builder (IB), which allowed you to build and customize your project’s user interface. One of the major changes introduced in later versions of Xcode integrated Interface Builder into the workspace itself. Interface Builder is no longer a separate stand-alone application, which means you don’t need to jump back and forth between Xcode and Interface Builder as your code and interface evolve.
You’ll be working extensively with Xcode’s interface-building functionality throughout the book, digging into all the various details. In fact, you’ll start working with Interface Builder later in this chapter.
Integrated Compiler and Debugger
Xcode has a fast, smart compiler and low-level debugger , which improve with each release.
For many years, Apple used the GNU Compiler Collection (GCC) as the basis for its compiler technology. But over the course of the past few years, it has shifted over completely to the Low Level Virtual Machine (LLVM) compiler . LLVM generates code that is faster by far than that generated by the traditional GCC. In addition to creating faster code, LLVM knows more about your code, so it can generate smarter, more precise error messages and warnings.
Xcode is also tightly integrated with LLVM, which gives it some new superpowers. Xcode can offer more precise code completion, and it can make educated guesses as to the actual intent of a piece of code when it produces a warning and offers a pop-up menu of likely fixes. This makes errors such as misspelled symbol names and mismatched parentheses a breeze to find and fix.
LLVM brings to the table a sophisticated static analyzer that can scan your code for a wide variety of potential problems, including problems with memory management. In fact, LLVM is so smart about this that it can handle most memory management tasks for you, as long as you abide by a few simple rules when writing your code. You’ll begin looking at the new feature called Automatic Reference Counting (ARC) in the next chapter.
Taking a Closer Look at the Hello World Project
Now that you’ve explored the Xcode project window, let’s take a look at the files that make up your new Hello World project. Switch to the Project Navigator by clicking the leftmost of the eight navigator icons in your workspace (as discussed in the “The Navigator” section earlier in the chapter) or by pressing ⌘1.
Note
You can access the eight navigator configurations using the keyboard shortcuts ⌘1 to ⌘8. The numbers correspond to the icons starting on the left, so ⌘1 is the Project Navigator, ⌘2 is the Symbol Navigator, and so on, up to ⌘8, which takes you to the Report Navigator.
The first item in the Project Navigator list bears the same name as your project—in this case, Hello World. This item represents your entire project, and it’s also where project-specific configuration can be done. If you single-click it, you’ll be able to edit a number of project configuration settings in Xcode’s editor. You don’t need to worry about those project-specific settings now, however. At the moment, the defaults will work fine.
Flip back to Figure 2-8. Notice that the disclosure triangle to the left of Hello World is open, showing a number of subfolders (which are called groups in Xcode).
Hello World: The first group, which is always named after your project, is where you will spend the bulk of your time. This is where most of the code that you write will go, as will the files that make up your application’s user interface. You are free to create subgroups under the Hello World group to help organize your code. You’re even allowed to add groups of your own if you prefer a different organizational approach. While you won’t touch most of the files in this folder until the next chapter, there is one file you will explore when you use Interface Builder in the next section. That file is called Main.storyboard, and it contains the user interface elements specific to your project’s main view controller. The Hello World group also contains files and resources that aren’t Swift source files but that are necessary to your project. Among these files is one called Info.plist, which contains important information about the application, such as its name, whether it requires any specific features to be present on the devices on which it is run, and so on. In earlier versions of Xcode, these files were placed into a separate group called Supporting Files.
Hello WorldTests: This group is created if you enable unit testing for the project (you didn’t, so it’s not there for this project), and it contains the initial files you’ll need if you want to write some unit tests for your application code. I’m not going to talk about unit testing in this book, but it’s nice that Xcode can set up some of these things for you in each new project you create if you want. Like the Hello World group, this one contains its own Info.plist file.
Products: This group contains the application that this project produces when it is built. If you expand Products, you’ll see an item called Hello World.app, which is the application that this particular project creates. If the project had been created with unit testing enabled, it would also contain an item called Hello WorldTests.xctest, which represents the testing code. Both of these items are called build targets. Because you have never built either of these, they’re both red, which is Xcode’s way of telling you that a file reference points to something that is not there.
Note
The “folders” in the navigator area do not necessarily correspond to folders in your Mac’s file system. They are just logical groupings within Xcode that help you keep everything organized and make it faster and easier to find what you’re looking for while working on your application. Often, the items contained in those groups are stored directly in the project’s directory, but you can store them anywhere—even outside your project folder if you want. The hierarchy inside Xcode is completely independent of the file system hierarchy, so moving a file out of the Hello World group in Xcode, for example, will not change the file’s location on your hard drive.
Introducing Xcode’s Interface Builder
In your project window’s Project Navigator, expand the Hello World group, if it’s not already open, and then select the Main.storyboard file. As soon as you do, the file will open in the editor pane, as shown in Figure 2-17. You should see something resembling an all-white iOS device centered on a plain white background, which makes a nice backdrop for editing interfaces. This is Xcode’s Interface Builder , which is where you’ll design your application’s user interface.
Figure 2-17. Selecting Main.storyboard in the Project Navigator opens the file in Interface Builder
Interface Builder has a long history. It has been around since 1988 and has been used to develop applications for NeXTSTEP, OpenStep, OS X, macOS, and now iOS devices such as the iPhone, iPad, Apple TV, and Apple Watch.
Introducing File Formats
Interface Builder supports a few different file types. The oldest is a binary format that uses the extension .nib, now an XML-based format using the .xib extension. Both of these formats contain exactly the same sort of document, but the .xib version, being a text-based format, has many advantages, especially when you’re using any sort of source control software. For the first 20 years of Interface Builder’s life, all of its files had the .nib extension. As a result, most developers took to calling Interface Builder files nib files. Interface Builder files are often called nib files, regardless of whether the extension actually used for the file is .xib or .nib. In fact, Apple sometimes uses the terms nib and nib file interspersed through its documentation.
Each nib file can contain any number of objects, but when working on iOS projects, each one will usually contain a single view (often a full-screen view) and the controllers or other objects to which it connects. This lets you compartmentalize your applications, loading the nib file for a view only when it’s needed for display. The end result is that you save memory when your app is running on a memory-constrained iOS device. A newly created iOS project has a nib file called LaunchScreen.xib that contains a screen layout that will be shown, by default, when your application launches. I’ll talk more about this file at the end of the chapter.
The other file format that IB has supported for the past few years is the storyboard. You can think of a storyboard as a “meta-nib file” since it can contain several view controllers , as well as information about how they are connected to each other when the application runs. Unlike a nib file, the contents of which are loaded all at once, a storyboard cannot contain freestanding views, and it never loads all of its contents at once. Instead, you ask it to load particular controllers when you need them. The iOS project templates in Xcode 8 all use storyboards, so all of the examples in this book will start with a storyboard. Although you get only one storyboard for free, you can add more if you need them. Now let’s go back to Interface Builder and the Main.storyboard file for the Hello World application (see Figure 2-17).
Exploring the Storyboard
You’re now looking at the primary tool for building user interfaces for iOS apps. Let’s say you want to create an instance of a button. You could create that button by writing code, but creating an interface object by dragging a button out of a library and specifying its attributes is so much simpler, and it results in the same thing happening at runtime.
The Main.storyboard file you are looking at right now loads automatically when your application launches (for the moment, don’t worry about how), so it is the right place to add the objects that make up your application’s user interface. When you create objects in Interface Builder, they’re instantiated in your program when the storyboard or nib file in which you added them loads. You’ll see many examples of this process throughout the book.
Every storyboard gets compartmentalized into one or more view controllers, and each view controller has at least one view. The view is the part you can see graphically and edit in Interface Builder, while the controller is application code you will write to make things happen when a user interacts with your app. The controllers are where the real action of your application happens.
In IB, you often see a view represented by a rectangle indicating the screen of an iOS device (actually, it represents a view controller , a concept that you’ll be introduced to in the next chapter, but this particular view controller covers the whole screen of the device, so it’s pretty much the same thing). Near the bottom of the IB window you’ll see a drop-down control that begins with View as, with a default device type. Click the device type. You can choose which device you’ll be creating the layout for, as shown in Figure 2-18.
Figure 2-18. In Xcode 8, IB lets you select the device type and orientation that you work in
Returning to the storyboard, click anywhere in the outline and you’ll see a row of three icons at the top of it, like those shown in Figure 2-17. Move your mouse over each of them and you’ll see tooltips pop up with their names: View Controller, First Responder, and Exit. Forget about Exit for now and focus instead on the other two.
View Controller: This represents a controller object that is loaded from file storage along with its associated view. The task of the view controller is to manage what the user sees on the screen. A typical application has several view controllers, one for each of its screens. It is perfectly possible to write an application with just one screen, and hence one view controller, and many of the examples in this book have only one view controller.
First Responder: This is, in basic terms, the object with which the user is currently interacting. If, for example, the user is currently entering data into a text field, that field is the current first responder. The first responder changes as the user interacts with the user interface, and the First Responder icon gives you a convenient way to communicate with whatever control or other object is the current first responder , without needing to write code to determine which control or view that might be.
I’ll talk more about these objects starting in the next chapter, so don’t worry if it’s a bit confusing right now determining when you would use a first responder or how a view controller gets loaded.
Apart from those icons, the rest of what you see in the editing area is the space where you can place graphical objects. But before you get to that, there’s one more thing you should see about IB’s editor area: its hierarchy view. This view is the Document Outline, as shown in Figure 2-19.
Figure 2-19. The Document Outline contains a useful hierarchical representation of the storyboard contents
If the Document Outline is not visible, click the little button in the lower-left corner of the editing area, and you’ll see it slide in from the left. It shows everything in the storyboard, split up into scenes containing chunks of related content. In this case, you have just one scene, called View Controller Scene. You can see that it contains an item called View Controller, which in turn contains an item called View (along with some other things you’ll learn about later). This provides a good way to get an overview of the content where everything you see in the main editing area is mirrored here.
The View icon represents an instance of the UIView class. A UIView object is an area that a user can see and interact with. In this application, you currently have only one view, so this icon represents everything that the user can see in your application. Later, you’ll build more complex applications that have several views. For now, just think of this view as an object that the user can see when using your application.
If you click the View icon, Xcode will automatically highlight the square screen outline that I was talking about earlier. This is where you can design your user interface graphically.
Exploring the Utilities Area
The Utilities area makes up the right side of the workspace. If it’s not currently selected, click the rightmost of the three View buttons in the toolbar, select View ➤ Utilities ➤ Show Utilities, or press⌥⌘0 (Option-Command-Zero). The bottom half of the Utilities area, shown in Figure 2-20, is the Library pane, or just plain library.
Figure 2-20. In the library you’ll find stock objects from the UIKit that are available for use in Interface Builder. Everything above the library but below the toolbar is known collectively as the inspector.
The library provides a collection of reusable items for use in your own programs . The four icons in the bar at the top of the library divide it into four sections. Click each icon in turn to see what’s in each section.
File Template Library: This section contains a collection of file templates you can use when you need to add a new file to your project. For example, if you want to add a new Swift source file to your project, one way to do it is to drag one type from the File Template Library and drop it onto the Project Navigator.
Code Snippet Library: This section features a collection of code snippets you can drag into your source code files. If you’ve written something you think you’ll want to use again later, select it in your text editor and drag it to the Code Snippet Library.
Object Library: This section contains reusable objects, such as text fields, labels, sliders, buttons, and just about any object you would ever need to design your iOS interface. You’ll use the Object Library extensively in this book to build the interfaces for the sample programs.
Media Library: As its name implies, this section is for all your media, including pictures, sounds, and movies. It’s empty until you add something to it.
Note
The items in the Object Library come from the iOS UIKit, which is a framework of objects used to create an app’s user interface. UIKit fulfills the same role in Cocoa Touch and as AppKit does in Cocoa on macOS. The two frameworks are similar conceptually; however, because of differences in the platforms, there are obviously many differences between them. On the other hand, the Foundation framework classes, such as NSString and NSArray, are shared between Cocoa and Cocoa Touch.
Note the search field at the bottom of the library . If you want to find a button, type button in the search field; the current library will show only items with button in the name. Don’t forget to clear the search field when you are finished searching; otherwise, not all the available items will be shown.
Adding a Label to the View
Let’s start working with IB. Click the Object Library icon (it looks like a circle with a square in the center—you can see it in Figure 2-20) at the top of the Library pane to bring up the Object Library. Just for fun, scroll through the library to find a table view. That’s it—keep scrolling and you’ll find it. But, there’s a better way: just type the words table view in the search field and you’ll see it appear.
Now find a label in the library. Next, drag the label onto the view you saw earlier. (If you don’t see the view in your editor pane, click the View icon in Interface Builder’s Document Outline.) As your cursor appears over the view, it will turn into the standard “I’m making a copy of something” green plus sign you know from the Finder. Drag the label to the center of the view. A pair of blue guidelines—one vertical and one horizontal—will appear when your label is centered. It’s not vital that the label be centered, but it’s good to know that those guidelines are there; when you drop the label, it should appear, as shown in Figure 2-21.
Figure 2-21. I’ve found a label in the library and dragged it onto the view
User interface items are stored in a hierarchy. Most views can contain subviews; however, there are some, like buttons and most other controls, that can’t. Interface Builder is smart. If an object does not accept subviews , you will not be able to drag other objects onto it.
By dragging a label directly to the view you’re editing, you add it as a subview of that main view (the view named View), which will cause it to show up automatically when that view is displayed to the user. Dragging a label from the library to the view called View adds an instance of UILabel as a subview of your application’s main view.
Let’s edit the label so it says something profound. Double-click the label you just created and then type Hello, World!. Next, click off the label and then reselect it and drag the label to recenter it or position it wherever you want it to appear on the screen .
You’ve completed this part, so now let’s save it to finish up. Select File ➤ Save, or press ⌘S. Now check out the pop-up menu at the upper left of the Xcode project window, the one that says Hello World. This is actually a multisegment pop-up control. The left side lets you choose a different compilation target and do a few other things, but you’re interested in the right side, which lets you pick which device you want to run on. Click the right side and you’ll see a list of available devices. At the top, if you have any iOS device plugged in and ready to go, you’ll see it listed. Otherwise, you’ll just see a generic iOS Device entry. Below that, you’ll see a whole iOS Simulator section listing all the kinds of devices that can be used with the iOS simulator. From that lower section, choose iPhone 7 so that your app will run in the simulator, configured as if it were an iPhone 7 .
There are several ways to launch your application: you can select Product ➤ Run, press ⇧R, or press the Run button that’s just to the left of the simulator pop-up menu. Xcode will compile your app and launch it in the iOS simulator (see Figure 2-22).
Figure 2-22. Here’s your Hello World program running in the iPhone 7 simulator with iOS 11
Note
Prior to the added features of Xcode 8, the text would not automatically center and you would need to work with Auto Layout to add things called constraints to make sure that it was centered on any device.
That’s really all there is to your first app at its most basic level —and notice that you wrote no Swift code at all!
Changing Attributes
Back in Xcode single-click the Hello World label to select it, and notice the area above the Library pane. This part of the utility pane is called the inspector. The inspector is topped by a series of icons, each of which changes the inspector to view a specific type of data. To change the attributes of the label, you’ll need the fourth icon from the left, which brings up the Attributes Inspector (see Figure 2-23).
Figure 2-23. The Attributes Inspector showing your label’s attributes
Tip
The inspector, like the Project Navigator, has keyboard shortcuts corresponding to each of its icons. The inspector’s keyboard shortcuts start with ⌥⌘1 for the leftmost icon, ⌥⌘2 for the next icon, and so on. Unlike the Project Navigator, the number of icons in the inspector is context-sensitive, and it changes depending on which object is selected in the navigator and/or editor. Note that your keyboard may not have a key that’s marked ⌥. If it doesn’t, use the Option key instead.
Change the label’s appearance any way you like, feeling free to play around with the font, size, and color of the text. Note that if you change the font size, you’ll need to add an Auto Layout constraint to make sure that it has the correct size at run time. To do that, select the label and then choose Editor ➤ Size to Fit Content from the Xcode menu (see Figure 2-24). Once you’ve finished playing, save the file and select Run again. The changes you made should show up in your application, once again without writing any code.
Figure 2-24. Changing the font size larger will force you to change the layout constraints by selecting Size to Fit Content from the Editor menu
Note
Don’t worry too much about what all the fields in the Attributes Inspector mean because as you make your way through the book, you’ll learn a lot about the Attributes Inspector and what most of the fields do.
By letting you design your interface graphically, Interface Builder frees you to spend time writing the code that is specific to your application , instead of writing tedious code to construct your user interface.
Most modern application development environments have some tool that lets you build your user interface graphically. One distinction between Interface Builder and many of these other tools is that Interface Builder does not generate any code that must be maintained. Instead, Interface Builder creates user interface objects, just as you would in your own code, and then serializes those objects into the storyboard or nib file so that they can be loaded directly into memory at runtime. This avoids many of the problems associated with code generation and is, overall, a more powerful approach .
Adding the Finishing Touches
Let’s refine the application by making it feel more like an authentic iPhone app. First, run your project again. When the simulator window appears, press ⌘⇧H. That will bring you back to the iPhone home screen, as shown in Figure 2-25. Notice that the app icon now shows as a plain, default image.
Figure 2-25. The Hello World application shown on the home screen
Take a look at the Hello World icon at the top of the screen. To change from this boring, default image, you need to create an icon and save it as a Portable Network Graphics (.png) file. Actually, for best results, you should create five icons for the iPhone in the following sizes: 180 × 180 pixels, 120 × 120 pixels, 87 × 87 pixels, 80 × 80 pixels, and 58 × 58 pixels. There’s another set of four icons that are required if you plan to release your application for the iPad. You’ll also need an image that is 187 × 187 pixels for the iPad Pro. The reason for so many icons is because they are used on the home screen, in the Settings app, and in the results list for a Spotlight search. That accounts for three of them, but that’s not the end of the story—the iPhone 7/6s Plus, with its larger screen, requires higher-resolution icons, adding another three to the list. Fortunately, one of these is the same size as an icon from the other set, so you actually only need to create five versions of your application icon for the iPhone. If you don’t supply some of the smaller ones, a larger one will be scaled down appropriately; but for best results, you (or a graphic artist on your team) should probably scale it in advance.
Do not try to match the style of the buttons that are already on the device when you create the icons; your iPhone or iPad automatically rounds the edges. Just create normal, square images. You’ll find a set of suitable icon images in the project archive’s Hello World - icons folder.
Note
For your application’s icon, you must use .png images; in fact, you should actually use that format for all images in your iOS projects. Xcode automatically optimizes .png images at build time, which makes them the fastest and most efficient image type for use in iOS apps. Even though most common image formats will display correctly, use .png files unless you have a compelling reason to use another format.
Press ⌘1 to open the Project Navigator, and look inside the Hello World group for an item called Assets.xcassets. This is an asset catalog. By default, each new Xcode project is created with an asset catalog, ready to hold your app icons and other resource files. Select Assets.xcassets and turn your attention to the editor pane.
On the left side of the editor pane, you’ll see a column with an entry labeled AppIcon . Select this item, and to the right you’ll see an area with the text AppIcon in the upper-left corner, as well as dashed-line squares for the icons I just talked about (see Figure 2-26). This is where you’ll drag all of your app icons.
Figure 2-26. The AppIcon boxes in your project’s assets catalog. This is where you set your application’s icon.
In the Finder, open the Hello World - icons folder, select all the files, and drag the bunch of them to IB. Most of the icons should automatically fill with the correct name.
Note
Early beta releases of Xcode 9 did not support this autofill function at the time of this writing. Also, for now, you don’t need to worry about the 1024 iOS Marketing icon.
You’ll likely have a few empty squares left over where you’ll find the right file and drag them individually to make sure that there are no empty squares. You do this by comparing the file size as part of the name to the number of points on the square. Note, Figure 2-27, that you’ll need to find the double or triple size file if a square has 2× or 3× below it.
Figure 2-27. Be sure to match .png files to the proper size requirement for the icon
Now compile and run your app. When the simulator has finished launching, press ⌘⇧H to go to the home screen, and check out your icon (see Figure 2-28). To see one of the smaller icons in use, swipe down inside the home screen to bring up the Spotlight search field, and start typing the word Hello—you’ll see your new app’s icon appear immediately.
Figure 2-28. The new app icon for your Hello World app
Note
As you work through this book, your simulator’s home screen will get cluttered with the icons for the example applications you’ll be running. If you want to clear out old applications from the home screen, choose iOS Simulator ➤ Erase All Content and Settings from the iOS simulator’s hardware menu.
Exploring the Launch Screen
When you launched your application, you may have noticed the white launch screen that appeared while the application was being loaded. iOS applications have always had a launch screen . Since the process of loading an application into memory takes time (and the larger the application, the longer it takes), the purpose of this screen is to let the user see as quickly as possible that something is happening. Prior to iOS 8, you could supply an image (in fact, several images of different sizes) to act as your app’s launch screen. iOS would load the correct image and immediately display it before loading the rest of your application. Starting with iOS 8, you still have that option, but Apple now strongly recommends that you use a launch file instead of a launch image, or as well as a launch image if your application still needs to support earlier releases.
A launch file is a storyboard that contains the user interface for your launch screen. On devices running iOS 8 and newer, if a launch file is found, it is used in preference to a launch image. Look in the Project Navigator and you’ll see that you already have a launch file in your project—it’s called LaunchScreen.storyboard. If you open it in Interface Builder, you’ll see that it just contains a blank view, as shown in Figure 2-29.
Figure 2-29. Your application’s default launch file
Apple expects you to build your own launch screen using Interface Builder, in the same way as you would construct any other part of your application’s user interface. Apple recommends that you don’t try to create a complex or visually impressive launch screen, so follow those guidelines. Here, you’re just going to add a label to the storyboard and change the background color of the main view so that you can distinguish the launch screen from the application itself. As before, drag a label onto the storyboard, change its text to Hello World, and then use the Attributes Inspector (see Figure 2-23) to change its font to System Bold 32. Making sure that the label is selected, click Editor ➤ Size to Fit Content in the Xcode menu. Now center the label in the view and click Editor ➤ Resolve Auto Layout Issues ➤ Add Missing Constraints to add layout constraints that make sure that it stays there. Next, select the main view by clicking it in the storyboard or in the Document Outline and use the Attributes Inspector to change its background color. To do that, locate the Background control and choose any color you like—I chose green. Now run the application again. You’ll see the launch screen appear and then fade away as the application itself appears, as shown in Figure 2-30.
Figure 2-30. A green launch screen for the Hello World application
You can read more about the launch file , launch images, and application icons in Apple’s iOS Human Interface Guidelines document, which you’ll find online at https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LaunchImages.html .
Running the Application on a Device
Before bringing this chapter to a close, there’s one more thing I will cover. Let’s load your app and run it on an actual device. The first step is to connect an iOS device to your Mac using its charging cable. When you do that, Xcode should recognize it and will spend some time reading symbol information from it. You may also see security prompts on both your Mac and your device asking whether you want one to trust the other. Wait until Xcode finishes processing symbol files from the device (check the Activity View to see that) and then open the device selector in the toolbar. You should see your device listed there, as shown in Figure 2-31.
Figure 2-31. The list of devices and simulators now includes my iPhone 6 running iOS 11 beta
Select the device and click the Run button on the toolbar to start the process of installing and running the application on it. Xcode will rebuild the application and run it on your device. However, because I’m using an early beta release of Xcode 9, you may see a prompt like the one shown in Figure 2-32.
Figure 2-32. If the automated provision features fail, you may see this message
Note
Apple made improvements to the provisioning system back in Xcode 8, and many of these “fix issue” features have become obsolete. The process has become more seamless and successful. Here, I address the topic in a way to make sure that you complete the provisioning to get the app to run on your actual device.
Before you can install an application on an iOS device , it has to have a provisioning profile, and it needs to be signed. Signing the application allows the device to identify the author of the application and to check that the binary has not been tampered with since it was created. The provisioning profile contains information that tells iOS which capabilities, such as iCloud access, your application needs to have and which individual devices it can run on. To sign the application, Xcode needs a certificate and a private key.
Tip
You can read about code signing, provisioning profiles, certificates, and private keys in Apple’s App Distribution Workflows in the App Distribution Guide at https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide .
In the early days of iOS development, you had to sign in to your developer program account, manually create both of these items, and then register the test devices on which you want to install the application. This was a nontrivial and frustrating process. Xcode 7 was improved to be smart enough to do this for you, and Xcode 8 has improved things even more, so this should all just work; all you need do is to put an app on a device for testing. In some cases, for different specialized builds to be distributed to particular users, you’ll want to customize your provisioning process, but for your learning process, the default, easy-to-use mechanisms work just fine.
There are a couple of things that can go wrong. First, if you see a message saying that your app ID is not available, you’ll need to choose a different one. The app ID is based on the project name and the organization identifier that you chose when you created the project (see Figure 2-4). You’ll see this message if you used com.beginningiphone or another identifier that somebody else has already registered. To fix it, open the Project Navigator and select the Hello World node at the top of the project tree. Then click the Hello World node under the TARGETS section in the Document Outline . Finally, click the General button at the top of the editor area (see Figure 2-33).
Figure 2-33. Changing your application’s bundle identifier
The app ID that Xcode uses for signing is taken from the Bundle Identifier field in the editor. You’ll see that it contains the organization identifier that you selected when you created the project—it’s the part of the field that’s highlighted in Figure 2-33. Choose another value and try building again. Eventually, you should find an identifier that hasn’t already been used. When you’ve done that, make a note of it and be sure to use it to fill in the Organization Identifier field whenever you create a new project. Once you’ve done that correctly once, Xcode will remember it so you shouldn’t have to do it again.
The other thing that can go wrong is shown in Figure 2-34.
Figure 2-34. Failure to launch in iOS 9, 10, or 11
You’ll see this message only if you are not enrolled in the developer program . It means that your iOS device does not trust you to run applications signed with your Apple ID. To fix this, open the Settings application on the device and then go to General ➤ Profile. You’ll reach a page with a table that contains your Apple ID. Tap the table row to open another page that looks like Figure 2-35.
Figure 2-35. On iOS 9 and newer, developers without a developer program membership are not trusted by default
Summary
You should be pleased with the progress you’ve made in this chapter. Although it may not seem like you accomplished all that much, you actually covered a lot of ground. You learned about the iOS project templates, created an application, learned key knowledge about Xcode 9, started using Interface Builder, learned how to set your application icon, and discovered how to run your application on the simulator and on a real device.
The Hello World program, however, is a strictly one-way application. You show some information to the users, but you never get any input from them. In the next chapter, you’ll look at how to go about getting input from the user of an iOS device and taking actions based on that input.