Next Steps: Debugging, Documentation, and App Icons - Introducing iOS 8 (2015)

Introducing iOS 8 (2015)

Chapter 6. Next Steps: Debugging, Documentation, and App Icons

In this chapter, you will learn how to debug your code. Debugging is a critical item in any developer’s tool belt. The ability to debug properly can save you hundreds of hours. You will also learn how to read Apple’s documentation. The documentation is like an encyclopedia provided by Apple; it has the answers to all your tough questions. Finally, you will learn how to add an app icon and a launch image to your apps. Let’s keep building your knowledge base and get started.

Why Debugging?

A major part of developing software is making mistakes and solving issues. Issues, also known as bugs, are defined when an application is not running as expected. The process used to triage and troubleshoot issues is called debugging. Apple even provides a suite of tools inside of Xcode to assist with debugging.

Debugging is part of the development process; no matter how many apps you make, you will always have to debug. Just like spell check in Microsoft Word, just because you have written 500 essays doesn’t mean you won’t make spelling or grammar mistakes. Don’t be discouraged when you are debugging; remember it is part of the process, and you are improving the quality of your app.

There are two major types of issues: compile time and runtime.

Compile-Time Issues

To understand compile-time issues, you must understand how Xcode works behind the scenes. Xcode takes the Swift code and translates it into zeros and ones in order for an iOS device to understand it. This translation from Swift to zeros and ones is called compiling, also known asbuilding. It is important when your code is written that it builds properly; if it doesn’t build properly, your app will not launch and will not be able to run. Whenever you click the Play button in the upper-left corner of the screen, the build process is started. If the build succeeds, then the app is run in the simulator. If it fails, Xcode will show a red error. For example, take a look at this code:

var total = 100 + 40

var half = totla / 2

The second line in the code has a compile-time error; there is no variable declared with the name totla. This would trigger an error, and the build would fail. See Figure 6-1.

Issue Navigator

Figure 6-1. Issue Navigator

Xcode will also tell you the reason why the error was created. For example:

var total = 100 + 40

var half = totla / 2

//Use of Unresolved Identifier 'totla'

The reasons can sound a bit cryptic at first, but after a little while, it becomes more natural. In this case, Xcode is stating that an identifier, also known as a variable, is being used, but the variable is not found. This message translates to, “You are using a variable that doesn’t exist.” The variable totla doesn’t exist because of a spelling error. Changing totla to total will resolve the issue:

var total = 100 + 40

var half = total / 2

//Build Successful - No Errors

Do not be discouraged by issues. There will be issues that take minutes, hours, or even days to solve. But remember, making mistakes and solving them is the best way to learn. There is no better feeling than solving an issue that once looked impossible. A positive attitude and a little persistence go a long way.

Errors

A compile-time error could be a problem with the syntax, accessing a property, or matching the proper type. These issues are caught by Xcode and are highlighted with a red dot, and an exclamation point will appear on the left side of the faulty line. Xcode’s compile-time check is like Microsoft Word’s grammar and spell checking. If there is an error, the error is highlighted and suggested solutions are provided.

Xcode has the ability to suggest solutions to problems, called a Fix-It. If there is a suggested fix, the red dot will appear, but instead of an exclamation point, there will be a white dot. Click the white dot, and a small pop-up menu will appear. This menu will state the issue and a possible fix. Click the Fix-It option, and the proposed fix will automatically be added to your code.

Warnings

In some cases, Xcode may suspect an issue could arise during runtime. In this case, Xcode will issue warnings. This could be because the type for a variable is not declared, or a variable could be unused. If a warning is found, a small yellow triangle will appear on the left side of the faulty line. Click the warning to reveal the possible issue. More often than not, warnings are indeed important and should be treated like errors.

When the application is built, the number of errors and warnings are shown at the top of Xcode. If there are any errors, Xcode will stop building and present a Build Failed notice (Figure 6-2). However, if there are warnings but no errors, Xcode will continue to build and provide a notice that the build was successful. All errors and warnings are collected and organized in one location, the Issue Navigator.

Build Failed notice

Figure 6-2. Build Failed notice

The Issue Navigator is available on the left window inside of Xcode. Reveal the Issue Navigator by clicking the fourth icon from the left in the Project Navigator’s toolbar. The icon looks like a triangle with an exclamation point in it. Once the Issue Navigator is revealed, all the issues, errors, and warnings inside the project will be displayed in a list. Click the issue in question, and the Editor will automatically open the necessary file and highlight the problematic line of code. The Issue Navigator will also provide a description of the problem for each issue. This makes finding related issues much easier.

Runtime Issues

Runtime is when the application is running and the view is active. For example, a runtime issue could mean that the application is crashing whenever a particular button is tapped. Solving runtime errors can be more difficult than solving compile-time errors. It can be difficult to understand which line of code is executing if the application is currently running. This is where breakpoints are helpful. Breakpoints allow the developer to temporarily pause the application while it is running and watch the code execute line by line. The process used to go from line to line is calledstepping. Stepping through your code is like watching an instant replay in slow motion. You can see the replay frame by frame and get a better sense of what is happening.

A crash is when the app cannot handle an issue that occurs when it is running. This results in the app shutting down and the user losing access.

Breakpoints

The left side of the editor is called the gutter. To create a breakpoint, click in the gutter next to the line of code you would like to debug. A dark blue rectangle with a pointer on it will appear (Figure 6-3). This signals the application will pause here during the code execution.

Breakpoint

Figure 6-3. Breakpoint

If a breakpoint is set and is active on the line of code that is currently executing, the application will stop and show the Debugger.

A new pane will display from the bottom called the debug area (Figure 6-4). The debug area has two parts: the variables view and the console. The variables view, located on the left side of the debug area, displays the current variables in the method.

Debug area

Figure 6-4. Debug area

Right-click a variable and select “Print description of variable” to print a detailed description of the variable to the console. The console on the right side of the debug area displays the developer log as the application is running (Figure 6-5). The console is a great way to monitor an application as it is running.

Console

Figure 6-5. Console

The println() method provides a simple way to print a message in the console. For example:

println("Button Tapped")

The println() method takes one parameter, a string, that is printed directly to the console when executed.

Using the Debugger

The variable view in Figure 6-6 is the debug toolbar. Table 6-1 shows each button on the debug toolbar from left to right.

Debug toolbar

Figure 6-6. Debug toolbar

Table 6-1. Debug toolbar buttons

Button

Description

Show/Hide

Debug area

Enable or Disable Breakpoints

Breakpoints

Continue

Resumes app back to normal state or until next breakpoint

Step Over

Executes next line of code, like a frame-by-frame forward button

Step Into

Moves the debugging into a method, if applicable

Step Out

Moves the debugging out of a method, if applicable

Debug View Hierarchy

Displays view for debugging interface elements and view layouts

Simulate Location

Selects a city to simulate GPS coordinates

Method Name

Shows the current method being called

The step over button will be used the most frequently. This button provides a slow-motion frame by frame of the code execution, like an instant replay. The console is also another helpful tool to determine when a particular event has happened or was logged.

Documentation

Documentation is the holy grail of any programming language. The documentation describes how each method, class, property, or variable works. The documentation is a developer’s best friend and will help to provide required details like parameter types or return values for a particular method. Apple invests a large amount of time and resources into its documentation. If you have a question, the first place to check is the documentation.

You can open the documentation by clicking Window in the top menu bar and selecting “Documentation and API Reference” (Figure 6-7). The documentation window will appear. It’s a good habit to always have the documentation window open when you are developing.

Documentation menu bar

Figure 6-7. Documentation menu bar

The documentation window works a bit like a web browser (Figure 6-8). Search for a topic in the large input box and select a result from the list. The three-lined button to the left of the input box is the table of contents pane. This pane will display all the titles and sections the documentation has to offer for a particular subject. It also serves as a great tool to quickly navigate to a particular section. The small triangle inside the next button to the left shows the Library Navigator. The Library Navigator allows you to browse through the documentation instead of search. The forward and back buttons work as you would expect.

Documentation window

Figure 6-8. Documentation window

Finally, the main window will reflect the class, reference, or guide selected. In the case of a class, the documentation will provide a brief description of the class and then list all of the methods and properties available. Each method or property will have its description and example declaration. For methods, a description for each parameter and the return value is given. Finally, the documentation will state when the property or method was created (for example, “created in iOS 3.0”).

Sample Code

The documentation provides more than just documents and guides. The documentation also provides sample code and example projects from Apple. These example projects are a great way to learn and see how Apple’s technologies work together. For example, open the Library Navigator and open the iOS 8 library by clicking on the arrow. Open User Experience and then Sample Code and select HelloWorld. This is a sample project to show developers how to create a simple app that receives user input and display it on the user interface. Click Open Project to view the sample code.

How to Get the Most Out of Documentation

Every good developer puts time and energy into learning the documentation. This is the best way to become a more complete developer. Since the documentation is such an important piece of everyday development, there are a few tips and tricks you should know.

If you have a question about a particular class, keyword, or method, hover your mouse over it, hold the Option key, and click it. A Quick Help pop-up will be displayed (Figure 6-9). Here you will find the declaration, description, and a link to the Reference Documentation. Click the reference link to open the documentation, or Option–double-click the item to avoid the Quick Help and go straight to the documentation. Also, you can open the documentation by pressing Command+Shift+0 on your keyboard.

Quick Help

Figure 6-9. Quick Help

One of the most valuable pieces of information inside the documentation is the iOS Human Interface Guidelines. The iOS Human Interface Guidelines is a document that explains how to use the interface elements provided by Apple. This document is a must-read, and apps can be rejected from the App Store if they do not comply.

Every good developer is familiar with the documentation. You should make reading the documentation part of your development process. Understanding and learning the documentation is a skill that must be practiced. Browse the documentation to learn more about what frameworks and resources are available to you. Use the Library Navigator to dive into new topics and learn more.

App Icons

The app icon represents the app in the App Store, on the Home Screen, and even in Spotlight. The app icon is used in many sizes across many devices. The app icon sizes in Table 6-2 are required.

Table 6-2. Required universal app icons

Filename

Image size (px)

Description

iTunesArtwork.png

1024x1024

App Store Listing

Icon-60@3x.png

180x180

Retina HD Home Screen

Icon-60@2x.png

120x120

Retina Home Screen

Icon-76@2x.png

152x152

iPad Retina Home Screen

Icon-76.png

76x76

iPad Home Screen

Icon-40@3x.png

120x120

Retina HD Spotlight

Icon-40@2x.png

80x80

Retina Spotlight

Icon-40.png

40x40

Spotlight

Icon-29@3x.png

87x87

Retina HD Settings

Icon-29@2x.png

58x58

Retina Settings

Icon-29.png

29x29

Settings

More details on Retina and Retina HD will be provided in Chapter 7. It is highly recommended to name the files using the provided filenames. If they are not named properly, the icons can be easily confused during the import process. Once all the icons have been created, they must be added into Xcode.

To add the icons to Xcode, open the Project Navigator and click images.xcassets. This will open a bar on the left side of the Editor. Select AppIcon and a graph similar to a family tree will appear (Figure 6-10).

App icons

Figure 6-10. App icons

Drag each icon into its corresponding slot. Test the new icons by running the app in the iOS Simulator. After the app launches, from the top menu bar, select Hardware→Home, or Command+Shift+H, and the app icon will be displayed on the Home Screen.

Launch Image

A launch image is shown immediately when an app is launched. The launch image tells the user the app has launched and is currently loading. Without a launch image, the user will see a black screen and be left wondering if the app is actually working. Launch images are typically set to portrait orientation; however, a landscape launch image can also be provided. The best launch images are plain images that are similar to the first interface shown upon launch. For example, the Facebook app shows a light gray screen with a dark blue bar at the top.

Xcode automatically creates a launch image with your project. The LaunchScreen.xib file is used to define the look and feel for your app’s launch image. The LaunchScreen.xib file also uses Auto Layout, explained more in the next chapter, to properly position elements on different device sizes.

In this chapter, you learned how to debug your code. You can now solve issues faster than before. You also learned how to read the documentation. Make reading the documentation part of your everyday development process. The more you read the documentation, the wider the net of apps you can build. Finally, you learned how to add your own app icon and a launch image to your apps. Keep up the great work and move on to the exercise.

Exercise: Expanding the Passport App

This exercise will expand on the Passport app created in Chapter 5. This exercise will also walk through using the Debugger and documentation. Finally, the exercise will add app icons and a launch image to the app (Figure 6-11).

Home Screen

Figure 6-11. Home Screen

To get started, open Finder and then open the Passport project folder (Figure 6-12). Inside the folder there are three items. There are two folders and a Passport.xcodeproj file. Open the Passport folder.

Finder

Figure 6-12. Finder

The files shown in Figure 6-13 make up the application. The file hierarchy shown here is not the same as the file hierarchy shown in the Project Navigator inside Xcode. The Project Navigator’s organization and file hierarchy is purely superficial.

Passport project

Figure 6-13. Passport project

Three .swift files are shown; these files are named for the classes they represent. The Base.lproj folder holds the .storyboard file, and image.xcassets holds the app icons. Finally, the Info.plist file is used to store details about the app, like version number and the bundle identifier. Go back and double-click the .xcodeproj file to get started.

It is time to add another country to the list of countries shown in your Passport app. Open the CountriesTableViewController.swift file and place your cursor after “England” in the countries array. Then type a space followed by “Spain”; be sure this is all inside the brackets of the array. Click the Play button in the upper-left corner of your screen.

Oops! It appears there is an error with the code. Click the red dot on the left side, and a Fix-It will appear (Figure 6-14). Click the Fix-It, and a comma will be properly inserted into the array. Click the Play button in the upper-left corner of your screen.

Error

Figure 6-14. Error

When the app opens, tap the Show Countries button to view your new set of countries (Figure 6-15).

Countries visited

Figure 6-15. Countries visited

The country Spain is not properly displaying in the table view. Close the iOS Simulator and go back to the CountriesTableViewController.swift file.

Scroll down to the cellForRowAtIndexPath method. Place your cursor under the line that reads cell.textLabel.text = country. On the left side of the Editor is a light gray area just before the Project Navigator. This area is called the gutter; click inside the gutter just below thecell.textLabel.text = country line to create a breakpoint.

A blue arrow will appear on the left side of the Editor; this is the breakpoint (Figure 6-16). The breakpoint will pause the app and allow you to step through the creation of each row. This way you can get to the bottom of this issue. Click the Play button in the upper-left corner to get started.

Setting a breakpoint

Figure 6-16. Setting a breakpoint

Once the app has started, click the Show Countries button. You will notice the Simulator is hidden, and Xcode is brought back into view. The breakpoint line is highlighted in green, and the Debugger is shown at the bottom of the Xcode window (Figure 6-17).

Debug area

Figure 6-17. Debug area

On the left side of the Debugger is a list of variables called the variables view. Notice the country variable is currently set to "Italy". Click the Continue button on the debug toolbar. The Continue button is the third icon from the left and looks like a Play button.

A loading indicator will appear quickly, and the green line will highlight the breakpoint line again. Look inside the variables view; the country variable is now set to "Norway". Click the Continue button on the debug toolbar.

A loading indicator will reappear quickly, and the green line will highlight the breakpoint line again. Look inside the variables view; the country variable is now set to "England". Click the Continue button on the debug toolbar.

The simulator reappears, and the same three countries are shown in the table view. The debugging session shows that cellForRowAtIndexPath is only being called three times.

Reopen CountriesTableViewController.swift and remove the breakpoint from the gutter. Take a look at numberOfRowsInSection and notice the return value is currently set to three. This means only three cells will be created. Replace the return line with the following code:

return countries.count

This new return line will provide the exact number of elements inside the countries array. Now there will always be a cell for each element in the countries array. Click the Play button in the upper-left corner to verify.

Congratulations—you just fixed your first bug!

Documentation

It would be nice if the cells displayed something other than just the country name. Scroll down to the cellForRowAtIndexPath method. Hold the Option key and click UITableViewCell. A small Quick Help box will appear (Figure 6-18). Click the UITableViewCell Class Referencelink.

Quick Help

Figure 6-18. Quick Help

The UITableViewCell documentation window will appear. On the left side is a table of contents. Scroll down and click accessoryType. The documentation states:

The accessory view appears in the right side of the cell in the table view’s normal (default) state. The standard accessory views include the disclosure chevron; for a description of valid accessoryType constants, see UITableViewCellAccessoryType.

Click UITableViewCellAccessoryType, and a list of values will appear:

§ None

§ DisclosureIndicator

§ DetailDisclosureButton

§ Checkmark

§ DetailButton

A checkmark on the right side of each country would be great. Close the documentation and place your cursor under the cell.textLabel.text = country line. Add the following code:

cell.accessoryType = .Checkmark

Click the Play button and notice the checkmark next to each country in the table view (Figure 6-19).

Checkmarks

Figure 6-19. Checkmarks

Congratulations—you just learned your first lesson from the documentation.

App Icon

It is now time to add an app icon to the project. Download the app icons from http://www.AppSchool.com/book.

Next, open Xcode alongside Finder. Drag the upper-right corner of the Xcode screen to make room for Finder (Figure 6-20). Inside the Project Navigator, click Images.xcassets and then click AppIcon. Drag the AppIcon sidebar to reveal all the icon slots if necessary.

Finder and Xcode

Figure 6-20. Finder and Xcode

Drag each file to the corresponding slot (Figure 6-21).

New app icons

Figure 6-21. New app icons

The app icon installation is now complete.

Open the LaunchScreen.xib file and remove the Passport Label (Figure 6-22). Select the Label and press Delete. Launch the application in the iOS Simulator.

LaunchScreen.xib

Figure 6-22. LaunchScreen.xib

Select Hardware→Home from the top menu bar to close the app and view the app icon (Figure 6-23).

New app icon

Figure 6-23. New app icon

Don’t worry if you received an error, a warning, or your app did not run as expected. The best way to learn is to make mistakes. Practice makes perfect. A sample version of the project is available on AppSchool.com/book. Download it, compare it, and try, try again. Don’t be afraid to start the exercise over and walk through it until you get it right.