Chapter 4
Hello World App Explained

Any fool can know. The point is to understand.

– Albert Einstein

Isn't it easy to build an app? I hope you enjoyed building your first app.

Before we continue to explore the iOS SDK, let's take a pause here and have a closer look at the Hello World app. It'll be good for you to understand the basics of the iOS APIs and the inner workings of the app.

So far you followed the step-by-step procedures to build the Hello World app. As you read through the chapter, you may have had a few questions in mind:

  • How does the View Controller in the storyboard link up with the ViewController class in the ViewController.swift file?
  • What does the block of code inside the showMessage(sender:) method mean? How does it tell iOS to show a Hello World message?
  • What does @IBAction keyword mean?
  • What is behind the "Hello World" button? How can the button detect tap and trigger the showMessage(sender:) method?
  • What is viewDidLoad()?
  • How does the Run button in Xcode work? What do you mean by "compile an app"?

I wanted you to focus on exploring the Xcode environment so I didn't explain any of the questions above. Yet it's essential for every developer to understand the details behind the code and grasp the basic concept of iOS programming. The technical concepts may be a bit hard to understand, in particular, if you have no prior programming experience. Don't worry because this is just the beginning. As you continue to study and write more code in the later chapters, you will gain a better understanding of iOS programming. Just try your best to learn as much as possible.

Understanding Implementation and Interface

Before diving into the programming concept, let's take a look at a real life example.

Consider a TV remote control. It's convenient to control the volume of a TV set wirelessly with a remote. To switch TV channels, you simply key in the channel number. To increase the speaker volume, you press the Volume + button.

Let me ask you. Do you know what happens behind the scene when pressing the Volume button or the channel button? Probably not. I believe most of us don't know how a remote control communicates with a TV set wirelessly. You may just think that the remote sends a certain message to the TV and triggers the volume increase or channel switch.

In this example, the button that interacts with you is commonly characterized as the interface and the inner details that hide behind the button are referred as the implementation. The interface communicates with the implementation via a message.

Figure 4-1. The TV Remote Control Analogy

This concept can also be applied in the iOS programming world. The user interface in storyboard is the interface, while the code is the implementation. The user interface objects (e.g. button) communicate with the code via messages.

Specifically, if you go back to the Hello World project, the button you added in the view is the interface. The showMessage(sender:) method of the ViewController class is the implementation. When someone taps the button, it sends a showMessageWithSender message to ViewController by invoking the showMessage(sender:) method.

What we have just demonstrated is one of the important concepts behind Object Oriented Programming known as Encapsulation. The implementation of the showMessage(sender:) method is hidden from the outside world (i.e. the interface). The Hello World button has no idea how the showMessage(sender:) method works. All it knows is that it needs to send a message. The showMessage(sender:) method handles the rest by displaying a "Hello World" message on the screen.

Quick note: Like Objective-C, Swift is an Object-Oriented Programming (OOP) language. Most of the code in an app in some ways deals with objects of some kind. I don't want to scare you away by teaching you the OOP concepts here. Just keep reading. As we go along, you'll learn more about OOP.

Behind the Touch

Now that you should have a basic understanding about how the button in the UI communicates with the code, let's take a look at what actually happens when a user taps the "Hello World" button? How does the "Hello World" button invoke the execution of the showMessage(sender:) method?

Do you remember how you established the connection between the Hello World button and the showMessage(sender:) event in Interface Builder?

Open Main again and select the "Hello World" button. Click the Connection inspector icon in the Utility area. Under the Sent Events section, you should find a list of available events and its corresponding method to call. As you can see in the figure below, the "Touch Up Inside" event is connected to the showMessage(sender:) method. Figure 4-2. Reveal the connections using Connection Inspector

In iOS, apps are based on event-driven programming. Whether it's a system object or UI object, it listens for certain events to determine the flow of the app. For a UI object (e.g. Button), it can listen for a specific touch event. When the event is triggered, the object calls up the preset method that associates with the event.

In the Hello World app, when users lift up the finger inside the button, the "Touch Up Inside" event is triggered. Consequently, it calls up the showMessage(sender:) method to display the "Hello World" message. We use the "Touch Up Inside" event instead of "Touch Down" because we want to avoid an accidental or false touch. The illustration shown in figure 4-3 sums up the event flow and what I have just described.

Figure 4-3. Event flow in the Hello World App
Figure 4-3. Event flow in the Hello World App

Inside the showMessage Method

You should now have a better understanding of iOS programming. But what is the block of code in the showMessage(sender:) method?

First things first, what is a method? As mentioned before, most of the code in an app in some ways deals with objects of some kinds. Each object provides certain functions and performs specific tasks (e.g. display a message on screen). These functions when expressed in code are known as methods.

Now, let's take a closer look at the showMessage(sender:) method.

Figure 4-4. showMessage() method explained
Figure 4-4. showMessage() method explained
Quick note: I know it may be a bit hard for you to understand the code. If you're completely new to programming, it'll take some time to get used to Object Oriented Programming. Don’t give up, as you’ll gain a better understanding of objects, classes, and methods as we move along. You can also take a look at the Appendix to learn more about the Swift syntax.

In Swift, to declare a method in a class, we use the func keyword. Following the func keyword is the name of the method. This name identifies the method and makes it easy for the method to be called elsewhere in your code. Optionally, a method can take in parameters as input. The parameters are defined within the parentheses. Each of the parameters should have a name and a type, separated by a colon (:). In our example, the method accepts a sender parameter which has a type UIButton. The sender parameter indicates the object that sends the request. In other words, it tells you the button that the user has tapped.

Note: Do you remember exercise #2 in the previous chapter? The sender parameter can tell you which emoji button the user has tapped. 

A method doesn't have to take in parameters. In this case, you simply write an empty pair of parentheses like this:

func showMessage()

There is one keyword in the method declaration that we haven't discussed. It's the @IBAction keyword. This keyword allows you to connect your source code to user interface objects in Interface Builder. When it is inserted in the method declaration, it indicates the method can be exposed to Interface Builder. This is why the showMessageWithSender event appeared in a pop-over when you established the connection between the Hello World button and the code in chapter 3. Refer to figure 3-19 if you do not understand what I mean.

Okay, enough for the method declaration. Let's talk about the block of code enclosed in the curly braces. The code block is the actual implementation of the task performed by the method.

If you look at the first line of the code block closely, we make use of UIAlertController to construct the Hello World message. What the heck is UIAlertController? Where does it come from?

When developing apps in iOS, we don't need to write all functions from scratch. Say, you don't need to learn how to draw the alert box on screen. The iOS SDK, bundled in Xcode, already provides you with tons of built-in functions to make your life easier. These functions are usually known as APIs and organized in the form of frameworks. The UIKit framework is just one of them, that provides classes and functions to construct and manage your app's user interface. For example, UIViewController, UIButton, and UIAlertController actually come from the UIKit framework.

There is one thing to take note. Before you can use any functions from the framework, you have to first import it. This is why you find this statement at the very beginning of ViewController.swift:

import UIKit

Now, let's continue to look into the showMessage(sender:) method.

The first line of code creates a UIAlertController object and store it in alertController. The syntax of constructing an object from a class is very similar to calling a method. You specify the class name, followed by a set of initial values of properties. Here we specify the title, message and preferred style of the alert:

let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: UIAlertController.Style.alert)

Right after creating the UIAlertController object (i.e. alertController), we call the addAction method to add an action to the alert so that it displays an "OK" button. When programming in Swift, you call a method by using dot syntax.

alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))

You may wonder how you can find out about the usage and available methods of a class. A simple answer is: Read the documentation. You can go up to Google to look up the class. But Xcode provides a convenient way to access the documentation of the iOS SDK.

In Xcode, you can press and hold the option key, point the cursor to the class name (e.g. UIAlertController) in your code and then click. A pop-over will appear displaying the class description and sample code. If you need further information, click the Open in Developer Documentation link. This will bring you to the official documentation of the class.

Figure 4-5. Class Information
Figure 4-5. Class Information

After the UIAlertController object is configured, the last line of the code is for showing the alert message on screen.

present(alertController, animated: true, completion: nil)

To display the alert, we ask the current view controller to present the alertController object with animation.

Sometimes, you may see some developers write the above line of code like this:

self.present(alertController, animated: true, completion: nil)

In Swift, you use the self property to refer to the current instance (or object). In most cases, the self keyword is optional. So you can omit it.

Relationship Between User Interface and Code

How does Xcode know that the View Controller in Interface Builder links up with the ViewController class defined in ViewController.swift?

The whole thing seems to be trivial but actually it is not. Do you remember the project template that we chose when creating the Xcode project? It is the App template.

When this project template is used, it automatically creates a default view controller in the Interface Builder editor and generates ViewController.swift. On top of that, the view controller is automatically linked with the ViewController class defined in the swift file.

Go to Main, select View Controller in the document outline view. In the Utility area, select the Identity inspector icon and you'll find that ViewController is set as the custom class. This is how the objects in Interface Builder associate with the classes in Swift code. Figure 4-6. Custom Class is set to ViewController

UIViewController and View Controller Life Cycle

Do you have questions about this part of the code? You know that ViewController is the name of the custom class, but what is UIViewController? And, what is viewDidLoad() method? Why was the method here?

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


  .
  .
  .

}

Like I said before, we rely on Apple's iOS SDK to build our apps. We rarely write our own code to draw a warning dialog or message dialog in order to present some messages on screen. We rarely draw our own buttons either. Instead, we rely on UIAlertController and UIButton to do the heavy lifting. The same concept applies to the view, the rectangular area we present on screen to users.

UIViewController is the fundamental building block of most iOS apps. It holds other UI elements (e.g. buttons) and controls what to display on screen. By default, UIViewController has an empty view. As you tested it in the previous chapter, it just displayed a blank screen without any functions or interactions with users. It is our responsibility to provide a custom version of UIViewController.

To do that, we create a new class (i.e. ViewController) that extends from UIViewController. By extending from UIViewController, ViewController inherits all its functionalities. For instance, it has a default empty view. In code, it is written like this:

class ViewController: UIViewController

In the body of ViewController, we provide our customizations. In the Hello World demo, we added a method called showMessage(sender:) to present a Hello World message.

This is one of the fundamental iOS development concepts you have to keep in mind. We are not writing everything from scratch. The iOS SDK already provides us with the skeleton of an iOS app. We build on top of the skeleton to create the UI and functionalities of our own app.

Now that I believe you have a basic idea of UIViewController, but what is viewDidLoad?

Similar to the "Hello World" button that we discussed earlier, the view of the view controller also receives different events due to the changes of the view's visibility or state. At an appropriate time, iOS automatically calls a specific method of UIViewController when the view's state changes.

When the view is loaded, the viewDidLoad method will be automatically called, so that you can perform additional initialization. In the Hello World app, we keep it unchanged. As a quick example, you can modify the method of your Hello World app like this to give it a try:

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.black
}

Run the app to have a quick test. The background of the view controller's view becomes black. This is one of the many examples when you need to customize the viewDidLoad() method. In later chapters, you will learn how we use viewDidLoad() for other customizations.

Figure 4-7. Changing the background color of the view
Figure 4-7. Changing the background color of the view

viewDidLoad is just one of the methods for managing the view's states. Say, when a user clicks the home button to go back to the Home screen, the viewWillDisappear and viewDidDisappear methods will be automatically called. Again, you can provide your own customization of these methods to perform additional operations.

Note: You have to add the override keyword before "func viewDidLoad()". This method is originally provided by UIViewController. In order to provide customizations, we indicate to override its default implementation by using the override keyword.

Behind the Scene of the Run Button

One final thing I would like to talk about is the Run button. When you click the Run button, Xcode automatically launches the simulator and runs your app. But what happens behind the scene? As a developer, you have to look at all the pieces.

The entire process can be broken into three phases: compile, package and run.

  • Compile – You probably think iOS understands Swift code. In reality, iOS only reads machine code. The Swift code is for developers to write and read. To make iOS understand the source code of the app, it has to go through a translation process to translate the Swift code into machine code. This process is referred as "compile". Xcode already comes with a built-in compiler to compile the source code.
  • Package – Other than source code, an app usually contains resource files such as images, text files, sound files, etc. All these resources are packaged to make up the final app. We used to refer to these two processes as the "build" process.
  • Run – This actually launches the simulator and loads your app.
Figure 4-8. Build Process
Figure 4-8. Build Process

Summary

You should now have a basic understanding of how the Hello World app works. As a beginner without any prior programming experience, it's not easy to understand all the programming concepts we just discussed. No worries. As you write more code and develop a real app in the upcoming chapters, you'll have a better idea about Swift and iOS programming.

To access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.

results matching ""

    No results matching ""