iOS App Development For Dummies (2014)

Part I. Getting Started

Chapter 3. The Nuts and Bolts of an Xcode Project

In This Chapter

arrow Getting a handle on your Xcode project

arrow Setting Xcode preferences

arrow Building and running an iPad app

arrow Getting inside the Simulator

arrow Adding application icons and images

To use Xcode to create an app, you need to create an Xcode project. An Xcode project includes all the files, resources, and information required to build your application. It's your partner in creating your application, and the sooner you make friends with it, the easier your life will become.

In this chapter, I show you how to create an Xcode project and then build and run your app in the Simulator.

Creating Your Project

Because developing an iPhone and/or an iPad app requires you to work in an Xcode project, it’s time to create one. The app you’ll be building is called RoadTrip (and will also be the name of the project). The app, as I mention in the Introduction to this book, is like a travel guide on your iOS device. Here’s how you get your RoadTrip project off the ground:

1.     Launch Xcode.

Simply go the Mac App Store, search for Xcode 5, click the Free button, and then click the Install App button that the Free button transmogrifies into, and you are done. After the download, you’ll find Xcode in your Applications folder. Double-click to launch it.

image Here are a couple of hints to make Xcode handier and more efficient right from the start:

·        Create a shortcut. Control-click the Xcode icon that appears in the Dock and then choose Options⇒Keep in Dock. You’ll be using Xcode a lot, so it wouldn’t hurt to be able to launch it from the Dock.

·        Nix the Welcome to Xcode screen if you’d like. When you first launch Xcode, you see the Welcome to Xcode screen with several links. (After you use Xcode to create projects, your Welcome screen lists all your most recent projects in the right column.) If you don’t want to be bothered with the Welcome screen in the future, deselect the Show This Window When Xcode Launches check box.

You can also just click Cancel to close the Welcome screen.

If you ever want to see the Welcome screen again, you can access it through the Window menu or by pressing Shift+image+1.

2.     Click the Create a New Xcode Project link on the left side of the Welcome screen, or choose File⇒New⇒Project to create a new project.

Alternatively, you can just press Shift+image+N.

No matter how you decide to start a new project, you’re greeted by the Choose a Template for Your New Project sheet (a “sheet” is also known as a “document-modal dialog”). Its purpose in life is pretty clear: It’s there to let you choose a new template for your new project. Note that the leftmost pane has two sections: one for iOS and the other for OS X (Apple’s name for the Macintosh operating system).

3.     In the upper-left corner of the Choose a Template dialog, select Application under the iOS heading (if it isn’t already selected).

After clicking Application, the main pane of the Choose a Template sheet refreshes, revealing several choices. (See Figure 3-1.) Each choice is actually a template that, when chosen, generates code to get you started.

4.     Select Master-Detail Application from the template choices displayed (as I have in Figure 3-1) and then click Next.

After you click Next, the Choose Options for Your New Project sheet appears.

image This Master-Detail Application template provides a starting point for the appropriately named Master-Detail application. What you get is a skeleton app with a split view. (I explain all about split views in the “The iPad’s Split views” section, later in this chapter.) A Split view is what you see in the Mail application. In Landscape orientation on the left is a Master view, and on the right is a Detail view. In Portrait orientation, you see the Detail view with a button that enables you to display the Master view in a popover.

image

Figure 3-1: Choose a template first.

Note that when you select a template, a brief description of the template is displayed underneath the main pane. (Again, refer to Figure 3-1 to see a description of the Master-Detail Application template.) In fact, go ahead and click some of the other template choices just to see how they’re described as well. Just be sure to click the Master-Detail Application template again when you're done, and then click Next, to follow along with developing the RoadTrip app.

image These template names do change from time to time, so don’t be surprised if yours are a little different from the ones I refer to in this book. For the most part, the kinds of application they build tend to stay the same.

5.     In the Choose Options for Your New Project sheet (see Figure 3-2), enter a name for your new project in the Product Name field, and add a company name (or your name) in the Organization Name field. For the Company Identifier, use your reverse domain name (com.yourdomain) if you have one.

If you don’t have one, you can make one up as long as you are not going to be submitting the app to the App Store.

I named this project RoadTrip. (You should do the same if you’re following along with developing RoadTrip.)

image

Figure 3-2: Choose project options.

Class prefix is something that will get prepended to the classes the template will generate, so enter RT (for RoadTrip) in the Class Prefix field. Prefixes are most often used to distinguish classes created by different teams so that if they are combined into a single project at a later date, duplicate names are avoided. (These are called namespace collisions.)

6.     Select Universal from the Devices Family pop-up menu (if it isn't already selected).

Doing so creates a skeleton app that will be configured to run on the iPad, iPhone, or iPod touch.

By choosing Universal, you're creating an app that can run on iPhone (and iPod touch) and iPad.

Any iPhone application will run on the iPad, but it doesn’t work the other way around unless you create a Universal application.

image I have you select Universal because, with the introduction of storyboards in iOS 5 and Xcode 4.2, creating a universal application has become much easier.

Do not select the Use Core Data check box. (Core Data is not covered in this book.)

7.     image Click Next and choose a location to save the project (the Desktop or any folder works just fine), do not select the Source Control: Create Local Git Repository check box, and then click Create.

Git is a software control management (SCM) system that keeps track of changes in the code and saves multiple versions of each file on your hard drive. Git can be used as a local repository — thus the Create Local Git Repository for This Project option — or you can install a Git server on a remote machine to share files among team members. Git is beyond the scope of this book — but if you want to find out more about it, check out the Xcode 5 User Guide (choose Help⇒Xcode User Guide).

After you click Create, Xcode creates the project and opens the Workspace window for the project — which should look like what you see in Figure 3-3.

image Xcode will remember your choices for your next project.

image

Figure 3-3: The Xcode Workspace window.

Exploring Your Project

Not to sound like a broken record, but to develop an iOS app, you have to work within the context of an Xcode project, very much like the one shown in Figure 3-3. This is, in effect, Command Central for developing your app; it displays and organizes your projects, source files, and the other resources needed to build your apps.

The project

image If the project isn't open, go ahead and open it in Xcode by tracking down the project file — on the Desktop, in a folder, wherever — and double-clicking it. When your project is launched in Xcode, the Navigator area appears on the left side of the Workspace window. When using the Master-Detail Application template — you did select the Master-Detail Application template when you created your project, right? — the following options may be selected for you by default:

·        The Utility and Debug areas are hidden.

·        The Navigator area is shown, with the Project navigator selected by default in the Navigator selector.

·        The project (RoadTrip, in this case) is selected in the Project navigator.

And as a result, the Project editor displays the RoadTrip project information in the Standard editor.

Long story short, when you launch your RoadTrip project in Xcode, what you see in the editor is the Project editor displaying the RoadTrip project.

image When I refer to (or ask you to select) the RoadTrip project in the Project Navigator, I am referring to the RoadTrip project that you see selected in Figure 3-3.

The Project editor

image Having your RoadTrip project selected in the Navigator area’s Project navigator (refer to Figure 3-3) sets a couple of balls rolling. In the first column of the Project editor, under the Project heading, you see the project itself. (A workspace can actually have more than one project, but you won’t be doing that in this book. One common use for a multi-project workspace is one that contains an iOS project, an OS X project, and some shared files.) A bit below the Project heading, you see the Targets heading. (Yes, there’s room for more than one target here as well.) Any project you create defines the default build settings for all the targets in that particular project. (Note that each target can also specify its own build settings, which could potentially override the project build settings.)

target is really just the app (the product you are building) and includes the information that Xcode requires to build the product from a set of files in a project or workspace — stuff like the build settings and build phases which you can see and edit in the Xcode project editor. A target inherits the build settings for the project, but you can override one or more of them by specifying different settings at the target level. There is one active target at a time, with the Xcode scheme (iPad Simulator for example) specifying the target.

The Project editor shows tabs across the top; clicking these tabs opens panes that enable you to examine and change project settings. Most of the default settings will work for your needs. The tabs are as follows:

·        General: There are five sections in General. Each can be opened and closed with the disclosure triangle next to its name. Most of the time all start opened. Here they are:

·        Identity: This section is filled in automatically, but each value can be changed. For now, leave the defaults. It contains your app’s bundle identifier, which is a unique identifier built from your organization name and project name, a version (1.0 to start) and a build (1.0 to start). You can select a development team (there’s more on this later in this chapter in the section “Setting Your Xcode Preferences”). You may see a warning saying “No matching code signing identity found” or a similar warning with regarding to provisioning profiles. You can safely ignore it for now.

·        Deployment Info: This is the deployment target (the minimum iOS version you’re writing for) as well as which devices you support (the default is Universal). For each device, you can specify the interface, which orientations you support, and the status bar style. For starters, simply leave the default values.

·        App Icons: This section lets you specify where the icons are. Before Xcode 5, the names determined which icon was which. Now, asset catalogs let you provide your own names even as you place the images in a structured interface. Asset catalogs are discussed in “Using Asset Catalogs” later in this chapter. You can still provide individual images, but the asset catalogs are easier for newcomers as well as experienced developers.

·        Launch Images: These are the images that are shown as the app is launching. They, too, can be stored in asset catalogs.

·        Linked Frameworks and Libraries: These are the iOS frameworks that you need to use. The Master-Detail Application template automatically includes CoreGraphics, UIKit, and Foundation. Don’t worry about these for now: just leave them there.

·        Capabilities: This is where you turn various features on and off. Each one can be opened or closed with a disclosure triangle. An on-off switch at the right controls each capability. Most have a description of the capability along with a notice about what will happen if you turn the capability on. In this book, I focus on the common features do not use any of the advanced capabilities.

·        image Info: If you actually created the RoadTrip project earlier in this chapter and were then to open the disclosure triangle next to the Supporting Files folder in the Project navigator, you’d see a file called RoadTrip-Info.plist. The Info tab contains more or less the same information as that file. An information property list file contains essential configuration information for a bundled executable (the executable code and the accompanying resources, such as the storyboard, nibs, images, sounds, and so on). The system uses these keys and values to obtain information about your application and how it's configured. As a result, all bundled executables (plug-ins, frameworks, and applications) are expected to have an information property list file.

There also are sections where you can specify the types of documents your app can read and write. RoadTrip doesn’t use documents, so you don’t need to worry about the settings on this section.

·        Build Settings: Most developers can get by with the default build settings, but if you have special requirements — ones that require anything from tweaking a setting or two to creating an entirely new build configuration — you’ll take care of them in this tab.

·        Build Phases: This tab has a number of sections that control how Xcode builds your products. For example, Xcode detects when one of your products is dependent on another and automatically builds those products in the correct order. However, if you need to tweak the order in which Xcode builds your products, you can use the Build Phases tab to create explicit target dependencies.

·        Build Rules: Xcode processes your source files according to file type using a set of built-in rules. For example, property list (plist) files are copied into the product using the CopyPlistFile script located in the Xcode directory. Because the built-in rules are fine for almost all circumstances, you won’t need to mess with this particular tab for a long time — and if you’re lucky, never.

The Project navigator

After your project is created, the Xcode workspace displays the Project navigator. I introduce the Project navigator in Chapter 2, but give you a full tour here.

image Xcode has a lot of context-based help. Whenever you’re curious about what something does, try Control-clicking on it, and you’ll likely find a menu with relevant commands including Help. In Figure 3-4, for example, I Control-clicked in the Project navigator to bring up a shortcut menu from which I can choose the Project Navigator Help menu.

image

Figure 3-4: Project navigator help.

image The Navigator area is an optional area on the left side of the Workspace window where you can load different navigators — including the Project navigator — with the help of the Navigator selector. To hide or show the Navigator area, click the left View selector button in the workspace toolbar, shown in Figure 3-5.

image

Figure 3-5: The View selector in the workspace toolbar.

The Navigator area includes the Navigator selector bar, the Content area, and the Filter bar. It can also include other features specific to the selected navigator.

image The Project navigator enables you to do things like add, delete, group, and otherwise manage files in your project or choose a file to view or edit in the Editor area. (Depending on which file you choose, you’ll see the appropriate editor.) In Figure 3-6, for example, you can see that I’ve decided to open all the disclosure triangles so that the Project navigator displays all the files in the project.

The Filter bar lets you restrict the content that's displayed — such as recently edited files, unsaved files, or filenames.

Making your way down the group structure shown in the Project navigator (refer to Figure 3-6), the first group listed is labeled RoadTrip.

image “What?” you may be saying. I see folders just like in the Finder. “What are these groups?” In the Project navigator, you can group files together. They are shown using folder icons just as in the Finder, but they are Xcode groups. The files may be in different folders on disk.

The RoadTrip group contains all the source elements for the project, including source code, resource files, graphics, and a number of other pieces that will remain unmentioned for now (but I get to those in due course). Although each template organizes these source elements in different ways, the Master-Detail Application template organizes the interface header and implementation code files (along with the Storyboard file(s) and a Supporting Files folder) inside the RoadTrip group. (For good measure, the RoadTrip group also includes a Frameworks folder and a Products folder.)

image

Figure 3-6: The RoadTrip Project navigator.

Here’s the kind of stuff that gets tossed into groups for projects like the RoadTrip project:

·        AppDelegate files: The AppDelegate.h and AppDelegate.m files contain the code for app-specific behavior that customizes the behavior of a framework object (so that you don’t have to subclass it — as I describe in Chapter 6). A behavior-rich framework object (used as-is) delegates the task of implementing one of its responsibilities to an application delegate for a very specific behavior. The delegation pattern of adding behaviors to objects is described in more detail in Chapter 6.

·        Storyboard: The storyboard files live in your project as the Main_iPad.storyboard file and the Main_iPhone.storyboard file (for a universal app), or just as a lone Main_whatever.storyboard file (for a device-specific app). With a storyboard, you can create and implement an overall view of the flow of your application and the user interface elements. I go into great detail on storyboards in Chapter 4. Soon you’ll like the .storyboard files as much as I do.

·        View controllers: The MasterViewController.h and MasterView
Controller.m files contain the code to control the initial view of the RoadTrip (based on the Master-Detail Application template). You’ll do a lot more with view controllers in later chapters.

·        Supporting Files: In this folder, you typically find the precompiled headers (header files that are compiled to reduce your application compilation time) of the frameworks you’ll be using — such as RoadTrip_Prefix.pch — as well as the property list (RoadTrip-Info.plist) andmain.m, your application’s main function. You may even find images and other media files, and some data files. The InfoPlist.strings file is used for localization (translating the text in your app to the user’s language preference). Default values are provided in your Info.plist file for items such as the copyright and the app name; InfoPlist.strings then provides language-specific versions of the values in <yourApp>-Info.plist. Each language has its own InfoPlist.strings in a folder for that language.

·        Frameworks: This folder holds the code libraries that act a lot like prefab building blocks for your app. (I talk about frameworks in Chapter 4.) By choosing the Master-Detail Application template, you let Xcode know that it should add the UIKit, Foundation, and CoreGraphicsframeworks to your project, because it expects that you’ll need them in this kind of application.

image You’ll be adding more frameworks yourself in addition to these three in developing RoadTrip. You find out how to add more frameworks in Chapter 8.

·        Products: The Products folder is a bit different from the others. In it, you’ll find the final RoadTrip.app file — not the source code of the app, but rather the built version of the app, which means that it has been translated from the source code into the object code for the iOS device’s processor to execute. At the moment, this file is listed in red because the file can’t be found.

image When a filename appears in red, this means that Xcode can’t find the underlying physical file. And because you've never compiled the RoadTrip app, it makes sense that the RoadTrip.app file (the app itself) is missing.

Setting Your Xcode Preferences

Xcode gives you options galore. I’m guessing that you won’t change any of them until you have a bit more programming experience under your belt, but a few options are actually worth thinking about now — so in this section, I show you how to set some of the preferences you might be interested in.

Follow these steps to set some of the preferences you’ll find useful:

1.     With Xcode open, choose Xcode⇒Preferences from the main menu.

2.     Click the Behaviors tab at the top of the Preferences window to show the Behaviors pane.

The Xcode Preferences window refreshes to show the Behaviors pane.

The left side of the pane shows the Events pane (the check marks indicate events for which settings are set), while the right side shows the possible actions for an event.

3.     Select (Running) Generates output in the left column and then choose the Show, Hide, or If No Output Hide option from the Debug area pop-up menu to the left of the debugger in the right pane.

This step controls what appears while you run your app. By default, you’ll find that the check box for showing the debugger in the Debug area is selected. (See Chapter 8 for more about debugging.)

4.     Select other options from the left column — perhaps (Build) Starts, (Build) Generates new issues, (Build) Succeeds, and (Build) Fails — and experiment with the options available.

You can link an event with playing a sound (something I like to do) or have an event trigger the Xcode icon bouncing up and down in the Dock. You can change many options in the Behaviors pane — too many to cover in this chapter! But take a look through them and experiment — they can make your life much easier.

Figure 3-7 shows the behaviors I have chosen if the run pauses. (By pause, I mean the run hits, say, a breakpoint; I cover breakpoints in Chapter 8.) I like to have a sound inform me in case I’m busy daydreaming (sosumi seems like the appropriate sound to play here).

image

Figure 3-7: Setting behaviors.

Figure 3-8 shows the behaviors I have chosen if a build fails. I like to use a sound for this occurrence as well. I also want to have the Issue navigator display. (See Chapter 8 for more about the value and use of the Issue navigator.) I also want it to navigate to the first new issue.

5.     Click the Downloads tab at the top of the Preferences window.

6.     Select the Check for and Install Updates Automatically check box, and then click the Check and Install Now button.

This step ensures that the documentation remains up-to-date and allows you to load and access other documentation.

7.     (Optional) Click the Fonts & Colors tab at the top of the Preferences window and use the options to change your workspace theme.

As you click the various theme options, you see a preview in the center of the window.

image

Figure 3-8: Choosing a behavior for when a build fails.

8.     (Optional) Click the Text Editing tab at the top of the Preferences window and set your text editing preferences.

I set the Indent width to 2 in the Indentation settings to get as much code on a line as possible.

9.     Click the red Close button in the top-left corner of the window to close the Xcode Preferences window.

Building and Running Your Application

image The Xcode toolbar (see Figure 3-9) is where you do things like run your application. I spell out the process a bit more here.

image

Figure 3-9: The Xcode toolbar.

The Flow controls are for defining, choosing, running, and stopping projects. They consist of the following:

·        Run button: Clicking the Run button builds and runs the targets — a target is a product to build and the instructions for building the product from a set of files in a project or workspace for the currently selected scheme. Pressing and holding the mouse button opens a menu — also available in the Product menu — that allows you to run, test, profile, or analyze your application.

Holding various modifier keys while clicking and holding the Run button allows you to select these other run options:

·        Control key: Run, test, or profile without building

·        Shift key: Build for running, testing, or profiling

·        Option key: Run, test, or profile

Regardless of the modifier key, Analyze is an option in each case.

·        Stop button: Terminates your (executing) application in the Simulator or the device.

·        Scheme menu: A scheme defines characteristics such as build targets, build configurations, and the executable environment for the product to be built. The scheme menu lets you select which scheme and which build destination you want to use. (I describe schemes in greater detail in the next section of this chapter.)

The Activity viewer shows the progress of tasks currently executing by displaying status messages, build progress, and other information about your project. For example, when you’re building your project, Xcode updates the Activity viewer to show where you are in the process — and whether the process completed successfully. If an Issues icon appears in the Activity viewer, click it to open the Issues navigator and look there for messages about your project. (None exist yet in Figure 3-9, so you won’t see an Issues icon there.)

The Workspace configuration includes the Editor and View controls (which I explain in Chapter 2).

Building an app

Building an app in Xcode means compiling all the source code files in the project. It’s really exciting (well, I exaggerate a bit) to see what you get when you build and run a project that you created from a template. Building and running an app is relatively simple; just follow these steps:

1.     In the toolbar, choose a scheme from the Scheme pop-up menu located to the right of the Run and Stop buttons.

scheme tells Xcode the purpose of the built product. The schemes in the Scheme pop-up menu specify which targets (actual products) to build, what build configuration to use when building them, which debugger to use when testing them, and which executable to launch when running them on the device or Simulator. You can use the default RoadTrip scheme for now.

2.     From the selected scheme, hold down the mouse button and slide to the right to choose your device or the simulator.

Choose one of the installed simulators. Do not choose iOS Device because that will run on a connected iPhone or iPad, and you need further preparation to do that.

3.     image Choose Product⇒Run from the main menu to build and run the application.

You can also click the Run button in the top-left corner of the Workspace window. The Activity viewer (shown in Figure 3-9) tells you all about the build progress, flags any build errors (such as compiler errors) or warnings, and (oh, yeah) tells you whether the build was successful.

Figure 3-10 shows you what you’ll see in the Simulator (in the Portrait mode) when you tap the Master button. (The Master button is located in the view that's underneath the master view controller at the left of Figure 3-10. Its purpose is to show the master view controller you see in Figure 3-10.) I know it’s not much to look at, but it's a start — and it is a functioning iPad app.

image

Figure 3-10: Not much of an app, but it is yours.

If you rotate the Simulator by choosing Hardware⇒Rotate Left, in the Simulator menu, you see a nice Split view (as shown in Figure 3-11). (I talk more about the mechanics behind this — the use of a Split view controller — in the next section, and in even more detail in Chapter 13.)

image

Figure 3-11: Your app in landscape mode.

The iPad’s Split views

Although it’s true that on the iPhone, you often see only one view at a time, on the iPad you get to see two views, courtesy of the Master-Detail Application template (and something called a Split view controller, which I explain in detail in Chapter 13). If you take another look at Figure 3-11, you can see what I’m talking about. The view on the left displays what is called the Master view. Although technically it could be any type of view you’d like, in the case of the Master-Detail Application template, you get something called a Table view, which displays a list of what are referred to as cells, entries, or rows. On the left side of Figure 3-12, I tapped the + button and you see a timestamp (in Coordinated Universal Time [UTC], the primary time standard and the successor to Greenwich Mean Time [GMT]) in the first cell in the master view. When I tap that cell, as I have on the right side of Figure 3-12, the same timestamp is displayed in the detail view and the cell is highlighted in the master view.

image

Figure 3-12: Splits aren’t just for bananas.

All the detail view does right now is display “Detail view content goes here.” Well, that’s not all it does. When you rotate the iPad into portrait mode, it’s also responsible for both displaying a nice Master button as well as for displaying the Master view in the popover that you see when you tap the nice Master button. (Refer to Figure 3-10.)

In landscape view, the master view on the left side also includes a toolbar with Edit and + bar button items that allow the user to modify content in this particular example program.

Again, it probably doesn’t seem like much, but (as you'll see when I explain the RoadTrip app in Chapter 4), this is pretty much all the “infrastructure” you’ll need to put together a really cool app.

The Log navigator

If you want to look at how the build works, now is as good a time as any to explain how the Log navigator works.

image Xcode generates a series of logs during the build process, which meticulously record the actions performed. You can view these logs by selecting the Log navigator, either by using the Navigator selector or by choosing View⇒Navigators⇒Show Log Navigator from Xcode’s main menu. In Figure 3-13, you can see a log of all my recent builds.

image

Figure 3-13: Build results.

The Log navigator lists these two types of actions:

·        Tasks: The Task log lists all the operations Xcode performed to carry out the task, such as building operations, archiving operations, and source control operations.

·        Sessions: A Session log is the transcript of the events that occurred during a session (a period during which an activity is performed). Running or debugging an application, for example, generates a session log that would include all debugger output.

The Log navigator contains the Task and Session list. When you select an item in this list, the corresponding log appears in the Log viewer. You can filter this list with the Filter bar.

It turns out you won’t need to use the Log navigator for the sample app in this book, simply because I have you examine all debug activity in the Debug area instead and any task-related issues in the Issue navigator.

image The ultimate success (or failure) of your build is also displayed in the Activity viewer.

Running in the Simulator

When you run your app, Xcode installs it on the Simulator (or on a real device if you specified a device as the active SDK) and launches it. Using the Hardware menu and your keyboard and mouse, the Simulator mimics most of what a user can do on a real device, albeit with some limitations that I point out shortly.

At first, the iPad Simulator looks like any iPad model would — kind of like what you can see back in Figure 3-11.

Interacting with your simulated hardware

Any simulator worth its salt has to be able to duplicate the actions you’d expect from a real device. The Xcode Simulator — no surprise here — can mimic a wide range of activities, all accessed from the Simulator Hardware menu. The Hardware menu items allow you to control various simulator behaviors, including

·        Choose a device. Switch the simulated device to an iPad, any model iPhone, or the Retina display found on iPhone 4, iPhone 4S, and fourth-generation iPod touch models.

·        Choose a version. Switch to a different version of iOS.

·        Rotate left. Choosing Hardware⇒Rotate Left rotates the Simulator to the left. If the Simulator is in Portrait view, it changes to Landscape view; if the Simulator is already in Landscape view, it changes to Portrait view.

·        Rotate right. Choosing Hardware⇒Rotate Right rotates the Simulator to the right. Again, if the Simulator is in Portrait view, it changes to Landscape view; if the Simulator is already in Landscape view, it changes to Portrait view.

·        Use a shake gesture. Choosing Hardware⇒Shake Gesture simulates shaking the device.

·        Go to the Home screen. Choosing Hardware⇒Home does the expected — you go to the Home screen.

·        Lock the Simulator (device). Choosing Hardware⇒Lock locks the Simulator, which then displays the Lock screen.

·        Send the running app low-memory warnings. Choosing Hardware⇒Simulate Memory Warning fakes out your app by sending it a (fake) low-memory warning.

·        Simulate the hardware keyboard. Choose Hardware⇒Simulate Hardware Keyboard to check out how your app functions when the device is connected to an optional physical keyboard dock or paired with a Bluetooth keyboard.

·        Choose an external display. To bring up another window that acts like an external display attached to the device, choose Hardware⇒TV Out and then choose 640 x 480, 1024 x 768, 1280 x 720 (720p), or 1920 x 1080 (1080p) for the window’s display resolution. Choose Hardware⇒TV Out⇒Disabled to close the external display window.

Making gestures

On the real device, a gesture is something you do with your fingers to make something happen in the device — a tap, a drag, a swipe, and so on. Table 3-1 shows you how to simulate gestures using your mouse and keyboard.

Table 3-1 Gestures in the Simulator

Gesture

iPad Action

Tap

Click the mouse.

Touch and hold

Hold down the mouse button.

Double tap

Double-click the mouse button.

Two-finger tap

1. Move the mouse pointer over the place where you want to start.

2. Hold down the Option key, which makes two circles appear that stand in for your fingers.

3. Click the mouse button.

Swipe

1. Click where you want to start and hold down the mouse button.

2. Move the mouse slowly in the direction of the swipe and then release the mouse button.

Flick

1. Click where you want to start and hold the mouse button down.

2. Move the mouse quickly in the direction of the flick and then release the mouse button.

Drag

1. Click where you want to start and hold down the mouse button.

2. Move the mouse slowly in the drag direction.

Pinch

1. Move the mouse pointer over the place where you want to start.

2. Hold down the Option key, which makes two circles appear that stand in for your fingers.

3. Hold down the mouse button and move the circles in (to pinch) or out (to unpinch).

Uninstalling apps and resetting your device

You uninstall applications on the Simulator the same way you do on the iPad, except you use your mouse instead of your finger. Follow these steps:

1.     On the Home screen, place the pointer over the icon of the app you want to uninstall and hold down the mouse button until all the app icons start to wiggle.

2.     Click the app icon’s Remove button — the little x that appears in the upper-left corner of the icon — to make the app disappear.

3.     Click the Home button (use Hardware⇒Home) to stop the other app icons from wiggling and finish the uninstall.

image On a separate note, you can always reposition an app’s icon on the Home screen by clicking and dragging it around with the mouse.

You can remove an application from the background the same way you’d do on the iPad, except that you use your mouse instead of your finger. Follow these steps:

1.     Simulate double-tapping the Home buttons with the keyboard equivalent Shift-Command-H twice.

2.     Scroll left and right with the mouse to locate the app you want to stop.

3.     Drag the view of the app up and out of the horizontal scrolling list of apps.

image To reset the Simulator to the original factory settings — which also removes all the apps you’ve installed — choose iOS Simulator⇒Reset Content and Settings, and then click Reset in the warning dialog that appears.

You have some of the basic apps installed on the Simulator — these include Settings. You can use Settings just as you do on an iOS device. This is particularly useful if you want to set an Apple ID for the Simulator to use. One reason for doing this would be to use the Simulator to test iCloud code in an app you have written. The app on the Simulator will use the Apple ID you have specified in Settings rather than the Apple ID under which you may be running on your app. iCloud on the Simulator is a new feature in iOS 7. This book doesn’t go into iCloud, but rest assured that when you’re ready to go there, the Simulator will be ahead of you.

Living with the Simulator’s limitations

Keep in mind that, despite the Simulator’s many virtues, running apps in the Simulator is still not the same thing as running them on an iOS device. Here’s why:

·        Different frameworks: The Simulator uses OS X versions of the low-level system frameworks, instead of the actual frameworks that run on the device. That means that occasionally some code may run fine in the Simulator but not on actual iOS devices. Although the Simulator is useful for testing functionality, there's no substitute for debugging the app on the device itself if you want to find out how it will really run.

·        Different hardware and memory: The Simulator uses the Mac hardware and memory. To accurately determine how your app will perform on an honest-to-goodness iOS device, you have to run it on a real iOS device.

·        Different installation procedure: Xcode installs your app in the Simulator automatically when you build the app using the iOS SDK. It’s a different kettle of fish to install your app on the device for testing. And, by the way, you don’t have a way to get Xcode to install apps from the App Store in the Simulator.

·        Lack of GPS: You can’t fake the Simulator into thinking that it’s lying on the beach at Waikiki.

image You can, however, choose to simulate a location in the Debug area.

·        Two-finger limit: You can simulate a maximum of two fingers. If your application’s user interface can respond to touch events involving more than two fingers, you need to test that on an actual device.

·        Accelerometer differences: You can access your computer’s accelerometer (if it has one) through the UIKit framework. Its reading, however, will differ from the accelerometer readings on an actual iPad (for some technical reasons that I don’t have the space to go into).

·        Differences in rendering: OpenGL ES (Open Graphics Library for Embedded Systems, in other words) is one of the many 3D graphics libraries that works with the iOS SDK. It turns out that the renderers it uses on devices are slightly different from the ones it uses in the iOS Simulator. As a result, a scene on the Simulator and the same scene on a device may not be identical at the pixel level.

·        Telephony: You can’t make a phone call on the iPhone simulator.

Using Asset Catalogs

Now that there are several screen sizes for iPhones and (currently) two resolutions, your images need to be managed in a more sophisticated way than in the past. Initially, images had specific names that indicated if they were icons, launch images, or other images. With Xcode 5, things are much simpler because instead of relying on naming conventions, you use asset catalogs.

Images inside an asset catalog are divided into sets. Each set contains one or more image representations. You create an asset catalog by creating a new file (File⇒New⇒File) and choosing Asset Catalog from the Resource section at the left of the window.

Figure 3-14 shows an asset catalog with three image sets in it — AppIcon, LaunchImage, and MyImage. The navigation at the left of the workspace window and the Utility area at the right are hidden. Inside the Editor area are two columns. At the left of the Editor area, a list of the sets is shown.

1.     Select the image set you want to work with in the set list.

In Figure 3-14, the App Icon set is selected. To follow along, select it now.

2.     Notice that the set viewer (the right-hand column in the asset catalog) now reflects the images of the selected set (AppIcon in this case).

There may be several representations of a single image reflecting the appropriate idioms (iPhone or iPad).

3.     If you want, you can change the name of the set either in the Status area or by double-clicking and editing the name in the set list.

You can also specify which representations (iPad, iPhone, Mac) you want to use at the top of the Status area and the appropriate scales for each (1x for non-Retina and 2x for Retina displays).

4.     Select the representation you want to work with in the Editing area.

The Status area at the right of the workspace window reflects the details for the selected representation below the set information.

image

Figure 3-14: Look inside an asset catalog.

An asset catalog can contain four types of images:

·        App icons: You may think you have a single app icon, but you would be wrong. You actually have an app icon image set with a multitude of idioms and scales. Each representation has its size shown both in the Editor area and in the Status area so that you know what you should be working with. (Remember that app icons are square, so only one dimension is provided.) It is best not to rename this set.

·        Launch images: These are images that are shown as early as possible in the app’s launch. They should provide the background of the first screen the user sees. When the launch is completed, the actual screen and its data appear. The effect is that the background is drawn and relevant text and graphics are drawn on top of it. There’s a launch image set in the Master-Detail template so you can explore it. Note that in the Status area, you can specify the details of the launch images, including not only the idiom but also the orientation. These are check boxes: You only have to provide the ones you choose. It is best not to rename this set.

·        Images: These are all the other images in your app. Using the button at the lower right of the Editor area, you can show the overview that lets you edit the representations for a specific image set (by defaults, there are two idioms and two scales, but this may well change over time). You can also look at image slicing, but that is an advanced topic that I don’t cover in this book. Each image will have its own image set.

·        OS X icons: For completeness, these are mentioned, but in this book, I focus on iOS.

You can see the representations for launch images in Figure 3-15.

You drag your images from your disk into the appropriate representation of the appropriate set. For app icons and launch images, if the image you try to drag is the wrong size, you will get an error. Note that for both app icons and launch images, there are different images for the different devices. Also note that there are separate versions for Retina (2X) and non-Retina (1X) displays.

If you are using one of the Xcode templates, you will have an asset catalog (usually called Images.xcassets) with an icon and launch images. You can add your own image sets to it. Figure 3-16 shows an image set called MyImage added to Images.xcassets. It has Retina and non-Retina display representations for Universal, iPhone, iPad, and Mac. (There is also a Retina display for the iPhone 4.)

image

Figure 3-15: Look at launch images.

image

Figure 3-16: Add your own image set.

You can choose the representations you want for your image set using the Editor⇒Device Image Reps submenu, as shown in Figure 3-17.

Many developers don't modify the template's asset catalog which contains the launch images and app icons. Instead, they create a separate asset catalog for their own image sets. Here's how to do that:

1.     Choose File⇒New⇒File.

2.     In the dialog that appears, select Resource under iOS at the left.

3.     Select Asset Catalog.

4.     Name and save the file in your project.

If you want, you can place the file in the Supporting Files group in your project (or anywhere else you choose).

Pre-Xcode 5 code for manipulating images was not pretty. Today, after you have set up your image catalog(s), you simply select the image set name that you want (often from a pop-up menu in the Utility area of a storyboard). At runtime, the appropriate image is chosen for you depending on the device in use. You don't have to do anything but use the image set name: iOS will choose the correct file.

image

Figure 3-17: Choose your image reps.

Adding the Image and Sound Resources and an App Icon

As a starter, you can download image and sound resources as well as an app icon. Here are the steps:

1.     Download the iOS 7 RoadTrip Resources folder from this book's companion website.

To find out how to access this book's companion website, please see the Introduction. Store the folder somewhere handy where you’ll be sure to find it again.

image This folder includes not only the application icon, but also a number of other resource files (images and sound) you’ll be using in your application.

You’ll start by adding the resources you’ll need.

2.     Control-click RoadTrip project in the Project Navigator, choose Add Files to “RoadTrip” from the contextual menu, use the dialog that appears to navigate to the RoadTrip Resources folder you downloaded, and then select non-image resources to add, such as sound files(.aif files). Choose File⇒Add Files to RoadTrip and pick the sound files.

Xcode asks you (via a check box in the aforementioned dialog) whether you want to make a copy of the file. If you don’t select the check box, Xcode creates a pointer (alias) to the file. The advantage of using an alias is that if you modify the file later, Xcode will use that modified version. The disadvantage is that Xcode won’t be able to find the file if you move it.

3.     Select the Copy Items into Destination Group’s Folder (If Needed) check box, make sure the check box in front of Road Trip in the Add to Targets section is selected, and then click Add to copy the files.

This adds the sound files you need.

image You can also drag sound files into the Project navigator.

4.     Create an image set for each named image and drag the appropriate representations (iPhone and iPad, for example) to that image set.

Note that these are a starter set of images. You will not have all the representations. For your own app, it's important to have all relevant representations.