Changes

Jump to: navigation, search

A Guided Tour of Xcode 6

23,061 bytes added, 17:20, 1 November 2016
no edit summary
<htmlet>ios10</htmlet>
 
Just about every activity related to developing and testing iOS applications involves the use of the Xcode environment. This chapter is intended to serve two purposes. Primarily it is intended to provide an overview of many of the key areas that comprise the Xcode development environment. In the course of providing this overview, the chapter will also work through the creation of a very simple iOS application project designed to display a label which reads “Hello World” on a colored background.
By the end of this chapter you will have a basic familiarity with Xcode and your first running iOS application.
 
== Starting Xcode 8 ==
 
As with all iOS examples in this book, the development of our example will take place within the Xcode 8 development environment. If you have not already installed this tool together with the latest iOS SDK refer first to the Installing Xcode 8 and the iOS 10 SDK chapter of this book. Assuming that the installation is complete, launch Xcode either by clicking on the icon on the dock (assuming you created one) or use the macOS Finder to locate Xcode in the Applications folder of your system.
 
When launched for the first time, and until you turn off the Show this window when Xcode launches toggle, the screen illustrated in Figure 4-1 will appear by default:
 
 
[[Image:|Image:]]
Figure 4-1
 
 
If you do not see this window, simply select the Window -> Welcome to Xcode menu option to display it. From within this window, click on the option to Create a new Xcode project. This will display the main Xcode project window together with the project template panel where we are able to select a template matching the type of project we want to develop:
 
 
[[Image:|Image:]]
Figure 4-2
 
 
The toolbar located on the top edge of the window allows for the selection of the target platform, providing options to develop an application for iOS, watchOS, tvOS or macOS.
 
Begin by making sure that the Application option located beneath iOS is selected. The main panel contains a list of templates available to use as the basis for an application. The options available are as follows:
 
• '''Master-Detail Application''' – Used to create a list based application. Selecting an item from a master list displays a detail view corresponding to the selection. The template then provides a Back button to return to the list. You may have seen a similar technique used for news based applications, whereby selecting an item from a list of headlines displays the content of the corresponding news article. When used for an iPad based application this template implements a basic split-view configuration.
• '''Page-based Application''' – Creates a template project using the page view controller designed to allow views to be transitioned by turning pages on the screen.
• '''Tabbed Application''' – Creates a template application with a tab bar. The tab bar typically appears across the bottom of the device display and can be programmed to contain items that, when selected, change the main display to different views. The iPhone’s built-in Phone user interface, for example, uses a tab bar to allow the user to move between favorites, contacts, keypad and voicemail.
• '''Single View Application''' – Creates a basic template for an application containing a single view and corresponding view controller.
• '''Game – Creates a project configured to take advantage of Sprite Kit, Scene Kit, OpenGL ES and Metal for the development of 2D and 3D games.
• '''iMessage Application''' – iMessage apps are extensions to the built-in iOS Messages app that allow users to send interactive messages such as games to other users. Once created, iMessage apps are made available for purchase through the Message App Store.
• '''Sticker Pack Application''' – Allows a sticker pack application to be created and sold within the Message App Store. Sticker pack apps allow additional images to be made available for inclusion in messages sent via the iOS Messages app.
 
For the purposes of our simple example, we are going to use the Single View Application template so select this option from the new project window and click Next to configure some more project options:
 
 
[[Image:|Image:]]
Figure 4-3
 
 
On this screen, enter a Product name for the application that is going to be created, in this case “HelloWorld”. The text entered into the Organization Name field will be placed within the copyright comments of all of the source files that make up the project.
 
The company identifier is typically the reversed URL of your company’s website, for example “com.mycompany”. This will be used when creating provisioning profiles and certificates to enable testing of advanced features of iOS on physical devices. It also serves to uniquely identify the app within the Apple App Store when the app is published.
 
The iOS ecosystem now includes a variety of devices and screen sizes. When creating a new project it is possible to indicate that the project is intended to target either the iPhone or iPad family of devices. With the gap between iPad and iPhone screen sizes now reduced by the introduction of the iPad Mini and iPhone Plus range of devices it no longer makes sense to create a project that targets just one device family. A much more sensible approach is to create a single project that addresses all device types and screen sizes. In fact, as will be shown in later chapters, Xcode 8 and iOS 10 include a number of features designed specifically to make the goal of universal application projects easy to achieve. With this in mind, make sure that the Devices menu is set to Universal.
 
Apple supports two programming languages for the development of iOS apps in the form of Objective-C and Swift. While it is still possible to program using the older Objective-C language, Apple considers Swift to be the future of iOS development. All the code examples in this book are written in Swift, so make sure that the Language menu is set accordingly before clicking on the Next button.
 
On the final screen, choose a location on the file system for the new project to be created and click on Create.
 
Once the new project has been created, the main Xcode window will appear as illustrated in Figure 4-4:
 
 
[[Image:|Image:]]
Figure 4-4
 
 
Before proceeding we should take some time to look at what Xcode has done for us. First, it has created a group of files that we will need to create our application. Some of these are Swift source code files (with a .swift extension) where we will enter the code to make our application work.
 
In addition, the Main.storyboard file is the save file used by the Interface Builder tool to hold the user interface design we will create. A second Interface Builder file named LaunchScreen.storyboard will also have been added to the project. This contains the user interface layout design for the screen which appears on the device while the application is loading.
 
Also present will be one or more files with a .plist file extension. These are Property List files which contain key/value pair information. For example, the Info.plist file contains resource settings relating to items such as the language, executable name and app identifier and, as will be shown in later chapters, is the location where a number of properties are stored to configure the capabilities of the project (for example to configure access to the user’s current geographical location). The list of files is displayed in the Project Navigator located in the left-hand panel of the main Xcode project window. A toolbar at the top of this panel contains options to display other information such as build and run history, breakpoints and compilation errors.
 
By default, the center panel of the window shows a general summary of the settings for the application project. This includes the identifier specified during the project creation process and the target device. Options are also provided to configure the orientations of the device that are to be supported by the application together with options to upload icons (the small images the user selects on the device screen to launch the application) and launch screen images (displayed to the user while the application loads) for the application.
 
In addition to the General screen, tabs are provided to view and modify additional settings consisting of Capabilities, Info, Build Settings, Build Phases and Build Rules. As we progress through subsequent chapters of this book we will explore some of these other configuration options in greater detail. To return to the project settings panel at any future point in time, make sure the Project Navigator is selected in the left-hand panel and select the top item (the application name) in the navigator list.
 
When a source file is selected from the list in the navigator panel, the contents of that file will appear in the center panel where it may then be edited. To open the file in a separate editing window, simply double-click on the file in the list.
 
== Creating the iOS App User Interface ==
 
Simply by the very nature of the environment in which they run, iOS apps are typically visually oriented. As such, a key component of just about any app involves a user interface through which the user will interact with the application and, in turn, receive feedback. While it is possible to develop user interfaces by writing code to create and position items on the screen, this is a complex and error prone process. In recognition of this, Apple provides a tool called Interface Builder which allows a user interface to be visually constructed by dragging and dropping components onto a canvas and setting properties to configure the appearance and behavior of those components.
 
As mentioned in the preceding section, Xcode pre-created a number of files for our project, one of which has a .storyboard filename extension. This is an Interface Builder storyboard save file and the file we are interested in for our HelloWorld project is named Main.storyboard. To load this file into Interface Builder simply select the file name in the list in the left-hand panel. Interface Builder will subsequently appear in the center panel as shown in Figure 4-5:
 
[[Image:|Image:]]
 
Figure 4-5
 
 
In the center panel a visual representation of the user interface of the application is displayed. Initially this consists solely of the UIView object. This UIView object was added to our design by Xcode when we selected the Single View Application option during the project creation phase. We will construct the user interface for our HelloWorld app by dragging and dropping user interface objects onto this UIView object. Designing a user interface consists primarily of dragging and dropping visual components onto the canvas and setting a range of properties. In order to access objects and property settings it is necessary to display the Xcode right-hand panel (if it is not already displayed). This panel is referred to as the Utilities panel and can be displayed by selecting the right-hand button in the right-hand section of the Xcode toolbar:
 
 
[[Image:|Image:]]
Figure 4-6
 
 
The Utilities panel, once displayed, will appear as illustrated in Figure 4-7:
 
[[Image:|Image:]]
 
Figure 4-7
 
 
Along the top edge of the panel is a row of buttons which change the settings displayed in the upper half of the panel. By default the File Inspector is displayed. Options are also provided to display quick help, the Identity Inspector, Attributes Inspector, Size Inspector and Connections Inspector. Before proceeding, take some time to review each of these selections to gain some familiarity with the configuration options each provides. Throughout the remainder of this book extensive use of these inspectors will be made.
 
The lower section of the panel may default to displaying the file template library. Above this panel is another toolbar containing buttons to display other categories. Options include frequently used code snippets to save on typing when writing code, the Object Library and the Media Library. For the purposes of this tutorial we need to display the Object Library so click on the appropriate toolbar button (represented by the circle with a small square in the center). This will display the UI components that can be used to construct our user interface. Move the cursor to the line above the lower toolbar and click and drag to increase the amount of space available for the library if required. The layout of the items in the library may also be switched from a single column of objects with descriptions to multiple columns without descriptions by clicking on the button located in the bottom left-hand corner of the panel and to the left of the search box.
 
== Changing Component Properties ==
 
With the property panel for the View selected in the main panel, we will begin our design work by changing the background color of this view. Start by making sure the View is selected and that the Attributes Inspector (View -> Utilities -> Show Attributes Inspector) is displayed in the Utilities panel. Click on the white rectangle next to the Background label to invoke the Colors dialog. Using the color selection tool, choose a visually pleasing color and close the dialog. You will now notice that the view window has changed from white to the new color selection.
 
== Adding Objects to the User Interface ==
 
The next step is to add a Label object to our view. To achieve this, either scroll down the list of objects in the Object Library panel to locate the Label object or, as illustrated in Figure 4-8, enter Label into the search box beneath the panel:
 
 
[[Image:|Image:]]
Figure 4-8
 
 
Having located the Label object, click on it and drag it to the center of the view so that the vertical and horizontal center guidelines appear. Once it is in position release the mouse button to drop it at that location. We have now added an instance of the UILabel class to the scene. Cancel the Object Library search by clicking on the “x” button on the right-hand edge of the search field. Select the newly added label and stretch it horizontally so that it is approximately three times the current width. With the Label still selected, click on the centered alignment button in the Attributes Inspector (View -> Utilities -> Show Attributes Inspector) to center the text in the middle of the label view.
 
[[Image:|Image:]]
 
Figure 4-9
 
 
Double-click on the text in the label that currently reads “Label” and type in “Hello World”. Locate the font setting property in the Attributes Inspector panel and click on the “T” button next to the font name to display the font selection menu. Change the Font setting from System – System to Custom and choose a larger font setting, for example a Georgia bold typeface with a size of 24 as shown in Figure 4 10:
 
[[Image:|Image:]]
 
Figure 4-10
 
 
The final step is to add some layout constraints to ensure that the label remains centered within the containing view regardless of the size of screen on which the application ultimately runs. This involves the use of the Auto Layout capabilities of iOS, a topic which will be covered extensively in later chapters. For this example, simply select the Label object, display the Align menu as shown in Figure 4 11 and enable both the Horizontally in Container and Vertically in Container options with offsets of 0 before clicking on the Add 2 Constraints button.
 
 
[[Image:|Image:]]
Figure 4-11
 
 
At this point, your View window will hopefully appear as outlined in Figure 4 12 (allowing, of course, for differences in your color and font choices).
 
 
[[Image:|Image:]]
Figure 4-12
 
 
Before building and running the project it is worth taking a short detour to look at the Xcode Document Outline panel. This panel appears by default to the left of the Interface Builder panel and is controlled by the small button in the bottom left-hand corner (indicated by the arrow in Figure 4-13) of the Interface Builder panel.
 
[[Image:|Image:]]
 
Figure 4-13
 
 
When displayed, the document outline shows a hierarchical overview of the elements that make up a user interface layout together with any constraints that have been applied to views in the layout.
 
[[Image:|Image:]]
 
Figure 4-14
 
 
== Building and Running an iOS 10 App in Xcode 8 ==
 
Before an app can be run it must first be compiled. Once successfully compiled it may be run either within a simulator or on a physical iPhone, iPad or iPod Touch device. For the purposes of this chapter, however, it is sufficient to run the app in the simulator.
 
Within the main Xcode project window, make sure that the menu located in the top left-hand corner of the window (marked C in Figure 4 15) has the iPhone 6 simulator option selected:
 
 
[[Image:|Image:]]
Figure 4-15
 
Click on the Run toolbar button (A) to compile the code and run the app in the simulator. The small panel in the center of the Xcode toolbar (D) will report the progress of the build process together with any problems or errors that cause the build process to fail. Once the app is built, the simulator will start and the HelloWorld app will run:
 
 
[[Image:|Image:]]
Figure 4-16
 
 
Note that the user interface appears as designed in the Interface Builder tool. Click on the stop button (B), change the target menu from iPhone 6 to iPad Air 2 and run the application again. Once again, the label will appear centered in the screen even with the larger screen size. Finally, verify that the layout is correct in landscape orientation by using the Hardware -> Rotate Left menu option. This indicates that the Auto Layout constraints are working and that we have designed a universal user interface for the project.
 
== Running the App on a Physical iOS Device ==
 
Although the Simulator environment provides a useful way to test an app on a variety of different iOS device models, it is important to also test on a physical iOS device. Regardless of whether or not you have joined the Apple Developer Program at this point, it is possible to run the app on a physical device simply by connecting it to the development Mac system and selecting it as the run target within Xcode.
 
With a device connected to the development system, and an application ready for testing, refer to the device menu located in the Xcode toolbar. There is a reasonable chance that this will have defaulted to one of the iOS Simulator configurations (in the case of Figure 4 17, this is the iPhone 6s simulator).
 
 
[[Image:|Image:]]
Figure 4-17
 
 
Switch to the physical device by selecting this menu and changing it to the device name as shown in Figure 4-18:
 
 
[[Image:|Image:]]
Figure 4-18
 
 
With the target device selected, make sure the device is unlocked and click on the run button at which point Xcode will install and launch the app on the device.
 
== Managing Devices and Simulators ==
 
Currently connected iOS devices and the simulators configured for use with Xcode can be viewed and managed using the Xcode Devices window which is accessed via the Window -> Devices menu option. Figure 4-19, for example, shows a typical Device screen on a system where an iPhone and an Apple Watch have been detected:
 
[[Image:|Image:]]
Figure 4-19
 
A wide range of simulator configurations are set up within Xcode by default. Other simulator configurations can be added by clicking on the + button located in the bottom left-hand corner of the window. Once selected, a dialog will appear allowing the simulator to be configured in terms of device, iOS version and name.
 
The button displaying the gear icon in the bottom left corner allows simulators to be deleted, renamed or removed from the Xcode run target menu.
 
== Dealing with Build Errors ==
 
As we have not actually written or modified any code in this chapter it is unlikely that any errors will be detected during the build and run process. In the unlikely event that something did get inadvertently changed thereby causing the build to fail it is worth taking a few minutes to talk about build errors within the context of the Xcode environment.
If for any reason a build fails, the status window in the Xcode toolbar will report that an error has been detected by displaying “Build” together with the number of errors detected and any warnings. In addition, the left-hand panel of the Xcode window will update with a list of the errors. Selecting an error from this list will take you to the location in the code where corrective action needs to be taken.
 
== Monitoring Application Performance ==
 
Another useful feature of Xcode is the ability to monitor the performance of an application while it is running. This information is accessed by displaying the Debug Navigator.
 
When Xcode is launched, the project navigator is displayed in the left-hand panel by default. Along the top of this panel is a bar with a range of other options. The sixth option from the left displays the debug navigator when selected as illustrated in Figure 4 20. When displayed, this panel shows a number of real-time statistics relating to the performance of the currently running application such as memory, CPU usage, disk access, energy efficiency, network activity and iCloud storage access.
 
[[Image:|Image:]]
 
Figure 4-20
 
 
When one of these categories is selected, the main panel (Figure 4 21) updates to provide additional information about that particular aspect of the application’s performance:
 
[[Image:|Image:]]
 
Figure 4-21
 
 
Yet more information can be obtained by clicking on the Profile in Instruments button in the top right-hand corner of the panel.
 
== An Exploded View of the User Interface Layout Hierarchy ==
 
Xcode also provides an option to break the user interface layout out into a rotatable 3D view that shows how the view hierarchy for a user interface is constructed. This can be particularly useful for identifying situations where one view object is obscured by another appearing on top of it or a layout is not appearing as intended. To access the View Hierarchy in this mode, run the application and click on the Debug View Hierarchy button highlighted in Figure 4-22:
 
 
[[Image:|Image:]]
Figure 4-22
 
 
Once activated, a 3D “exploded” view of the layout will appear. Note that it may be necessary to click on the Orient to 3D button highlighted in Figure 4-23 to switch to 3D mode:
 
 
[[Image:|Image:]]
Figure 4-23
 
 
Figure 4 24 shows an example layout in this mode for a slightly more complex user interface than that created in this chapter:
 
[[Image:|Image:]]
 
Figure 4-24
 
== Summary ==
 
Applications are primarily created within the Xcode development environment. This chapter has served to provide a basic overview of the Xcode environment and to work through the creation of a very simple example application. Finally, a brief overview was provided of some of the performance monitoring features in Xcode 8. Many more features and capabilities of Xcode and Interface Builder will be covered in subsequent chapters of the book.

Navigation menu