Hour 4. Inside Cocoa Touch


What You’ll Learn in This Hour:

Image What Cocoa Touch is and what makes it unique

Image The technology layers that make up the iOS platform

Image A basic iOS application life cycle

Image Classes and development techniques you’ll be using throughout this book

Image How to find help using the Apple developer documentation


When computers first started to appear in households almost 30 years ago, applications rarely shared common interface elements. It took an instruction manual just to figure out the key sequence to exit from a piece of software. Today, user interfaces (UIs) have been standardized so that moving from application to application doesn’t require starting from scratch.

What has made this possible? Not faster processors or better graphics, but frameworks that enforce consistent implementation of the features provided by the devices they’re running on. In this hour, we take a look at a few of the frameworks you’ll be using in your iOS applications.


You’ve Used the Word Framework Several Times. What Exactly Is a Framework?

A framework is simply a collection of the files (code, interface files, images, and so on) that provide functionality to an application. To use Apple Maps, for example, you use Apple’s MapKit framework. All of your apps include the Foundation, Core Graphics, and UIKit frameworks by default; otherwise they wouldn’t be able to do anything! Later in the book, we’ll build a few apps that require additional frameworks.


What Is Cocoa Touch?

In the preceding hour, you learned about the Swift language, the basic syntax, and what it looks like. Swift will form the functional skeleton of your applications. It will help you structure your applications, make logical decisions during the life cycle of your application, and enable you to control how and when events take place. What Swift doesn’t provide, however, is a way to access what makes your iDevice the compelling touch-driven platform that it is.

Consider the following Hello World statement:

print("Hello world!")

This line of code is a completely valid Swift application that, when executed, generates output that reads “Hello World.” You can compile this into an iOS project and execute it on your iPhone or iPad; but because iOS relies on Cocoa Touch for creating interfaces and handling user input and output, your users won’t see a thing.

Cocoa Touch is the collection of software frameworks that is used to build iOS applications and the runtime that those applications are executed within. It includes hundreds of classes for managing everything from buttons and uniform resource locators (URLs) to manipulating photos and performing facial recognition.

Cocoa Touch is the highest of several “layers” of services in the iOS and isn’t necessarily the only layer that you’ll be developing in. That said, you don’t need to worry too much about where Cocoa Touch begins and ends; the development will be the same, regardless. Later in this hour, you get an overview of iOS service layers.

Returning to the Hello World example, if we had defined a text label object named iOSOutput within a project, we could set it to read "Hello World" using Swift and the UILabel text variable property, just like this:

iOSOutput.text="Hello World"

Seems simple enough, as long as we know that the UILabel object has a text variable property, right?

Keeping Your Cool in the Face of Overwhelming Functionality

The questions that should be coming to most beginners right about now include these: I know there are many different features provided through iOS applications; how in the world will this book document all of them? How will I ever find what I need to use for my own applications?

These are great questions, and probably some of the biggest concerns that I’ve heard from those who want to program for the platform but have no idea where to start. The bad news is that we can’t document everything. We can cover the fundamentals that you need to start building, but even in a multivolume set of Teach Yourself books, there is so much depth to what is provided by Cocoa Touch that it isn’t feasible to create a comprehensive how-to reference.

The good news is that Cocoa Touch and the Apple developer tools encourage exploration. In Hour 6, “Model-View-Controller Application Design,” you start building interfaces visually using Xcode’s Interface Builder (IB) tools. As you drag objects (buttons, text fields, and so on) to your interface, you create instances of Cocoa Touch classes. The more you “play,” the quicker you will begin to recognize class names and variable properties and the role they play in development. Even better, Xcode developer documentation provides a complete reference to Cocoa Touch, enabling you to search across all available classes, methods, variable properties, and so on. We take a look at the documentation features later in this hour.

Young, Yet Mature

One of the most compelling advantages to programming using Cocoa Touch versus platforms such as Android is that although iOS and Swift are “young” platforms for Apple, the Cocoa frameworks are amazingly mature. Cocoa was borne out of the NeXTSTEP platform—the environment that was used by NeXT computers in the mid-1980s. In the early 1990s, NeXTSTEP evolved into the cross-platform OpenStep. Finally, in 1996, Apple purchased NeXT Computer, and over the next decade, the NeXTSTEP/OpenStep framework became the de facto standard for Macintosh development and was renamed Cocoa. You’ll notice that there are still signs of Cocoa’s origins in class names that begin with NS.


How Do Cocoa and Cocoa Touch Differ?

Cocoa and Cocoa Touch are not the same. Cocoa operates in a window-centric world with very different user events and far more capabilities due to running on machines with very fast processors and tons of RAM and storage.

The good news is that if you decide to transition from iOS developer to OS X developer, you’ll follow many of the same development patterns on both platforms; it won’t be like starting from scratch.


Exploring the iOS Technology Layers

Apple describes the technologies implemented within the iOS as a series of layers, with each layer being made up of different frameworks that can be used in your applications. As you might expect, the Cocoa Touch layer is at the top (see Figure 4.1).

Image

FIGURE 4.1 The technology layers that make up iOS.

Let’s review some of the more interesting frameworks that make up each of the layers. If you want a comprehensive guide to all frameworks, just search for each layer by its name in the Apple Xcode documentation.

The Cocoa Touch Layer

The Cocoa Touch layer is made up of several frameworks that will provide the core functionality for your applications, including multitasking and advertising. UIKit could be described as the “rock star” of this layer, delivering much more than the UI in its name implies.

UIKit

UIKit covers a wide range of functionality. It is responsible for application launching and termination, controlling the interface and multitouch events, and providing access to common views of data (including web pages and Word and Excel documents, among others).

UIKit is also responsible for many intra-iOS integration features. Accessing the Media Library, Photo Library, and accelerometer is also accomplished using the classes and methods within UIKit.

MapKit

The MapKit framework enables developers to add Apple’s map views to any application, including annotation, location, and event-handling features.

GameKit

The GameKit framework adds network-interactivity to iOS applications. GameKit supplies mechanisms for creating and using peer-to-peer networks, including session discovery, mediation, and voice chat. These features can be added to any application or game (or not).

Message UI/Contacts UI/EventKit UI

Apple is sensitive to the need for integration between iOS applications. The Message UI, Contacts UI, and EventKit UI frameworks can be used to access mail, contacts, and calendar events from any application you develop.

Notification Center

Create widgets and display information in the iOS notification center by using the Notification Center framework.

iAd

The iAd framework supports the addition of ads to your applications. iAds are interactive advertising pieces that can be added to your software with a simple drag and drop. You do not need to manage iAds interactions in your application; Apple does this for you.

TextKit

TextKit provides rich text rendering for iOS applications seeking to implement word-processor-like layout and font controls. TextKit includes features for editing, displaying, and saving rich content.

The Media Layer

When Apple makes a computing device, you’d better believe that they put some thought into the media capabilities. The iDevice family can create complex graphics, play back audio and video, and even generate real-time 3D graphics. The Media layer’s frameworks handle it all.

AV Foundation

The AV Foundation framework can be used to manage complex sound and video playback and editing. This should be used for implementing advanced features, such as movie recording, track management, and audio panning.

AVKit

The AVKit framework is used for simple video playback. It is also used to enable picture-in-picture playback under iOS 9 or later.

Core Audio

The Core Audio framework exposes methods for handling basic playback and recording of audio. It includes the AudioToolbox framework, which can be used for playing alert sounds or generating short vibrations, and the AudioUnit.framework for processing sounds.

Core Image

With the Core Image framework, developers can add advanced image and video processing capabilities to their applications without needing to understand the complex math behind them. Core Image, for example, provides facial-detection and image-filtering features that can easily be added to any application.

Core Graphics

Use the Core Graphics framework to add 2D drawing and compositing features to your applications. Although most of this book will use existing interface classes and images in its applications, you can use core graphics to programmatically manipulate the view.

Core Text

This provides precise positioning and control over text that is displayed on the screen. Core Text should be used in mobile text-processing applications and software that requires high-quality and fast presentation and manipulation of styled text.

Game Controller

Although not directly related to media, the Game Controller framework is also a member of the Media layer. This framework enables you to locate, connect, and configure game controllers that conform with Apple’s Made-for-iPhone (MFi) program.

Image I/O

The Image I/O framework can be used to import and export both image data and image metadata for any file format supported by iOS.

Metal

Metal is Apple’s new high-performance graphics framework. Unlike OpenGL, Metal provides much lower-level access to graphics hardware, enabling developers to push higher quality visuals in their apps.

OpenGL ES

OpenGL ES is a subset of the popular OpenGL framework for embedded systems (ES). OpenGL ES can be used to create 2D and 3D animation in your apps. Using OpenGL requires additional development experience beyond Swift but can generate amazing scenes for a handheld device—similar to what is possible on modern game consoles.

Photos

The Photos framework provides access to the Photos stored within an iOS library, including those on iCloud. Using this framework, you can create your own applications for managing and editing Photos in iOS.

Photos UI

Expand the capabilities of the Photos application by creating custom editing capabilities that can be used to extend the built-in iOS image editor.

SpriteKit

The SpriteKit framework provides a set of simple tools for animating graphics in 2D games. SpriteKit includes animation, collision detection, and object logic controls. If you’ve ever dreamed of making your own Mario-like world, SpriteKit is the place to start.

Quartz Core

The Quartz Core framework is used to create animations that will take advantage of the hardware capabilities of your device. This includes the feature set known as Core Animation.

The Core Services Layer

The Core Services layer is used to access lower-level operating system services, such as file access, iCloud storage, networking, and many common data object types. You’ll make use of core services often by way of the Foundation framework.

Accounts

Because of their always-connected nature, iOS devices are often used to store account information for many different services. The Accounts framework simplifies the process of storing and authenticating users.

Address Book

The Address Book framework is used to directly access and manipulate address book information. This is used to update contact information and display it within your applications.

CFNetwork

The CFNetwork framework provides access to BSD sockets, HTTP and FTP requests, and Bonjour discovery.

Core Data

The Core Data framework can be used to create the data model of an iOS application. Core Data provides a relational data model based on SQLite and can be used to bind data to interface objects to eliminate the need for complex data manipulations in code.

Core Foundation

Core Foundation provides much of the same functionality of the Foundation framework, but it is a procedural framework and therefore requires a different development approach that is, arguably, less efficient than Swift’s object-oriented model. You should probably avoid Core Foundation unless you absolutely need it.

Core Location

The Core Location framework can be used to obtain latitude and longitude information from the iPhone and iPad (3G/LTE) GPS (WiFi-based location service is available in non-3G/LTE devices, but is much less precise) along with a measurement of precision.

Core Motion

The Core Motion framework manages most motion-related events on the iOS platform, such as using the accelerometer or gyroscope.

EventKit

The EventKit framework is used to access calendar information stored on the iOS device. It also enables the developer to create new events within a calendar, including alarms.

Foundation

The Foundation framework provides an object-oriented wrapper around features in Core Foundation. Manipulation of strings, arrays, and dictionaries is handled through the Foundation framework, as are other fundamental application necessities, including managing application preferences, threads, and internationalization.

HealthKit

The HealthKit framework is used to store and access health-related data related to an iOS device user. If you are considering developing fitness-related apps, this framework is for you.

HomeKit

HomeKit provides a consistent interface to home automation hardware and tools. Using HomeKit, you can access automation functions across applications—additional hardware and software are necessary, however.

Newsstand

Use this framework to create periodical digital media, such as newspapers or magazines. The Newsstand framework supports automatic content updating, ensuring your customers see the most recent content without needing to manually update.

PassKit

The PassKit framework, coupled with web services, can provide electronic coupons, boarding passes, tickets, and other transaction information to the user.

Quick Look

The Quick Look framework implements file viewing within an application, even if the application does not “know” how to open a specific file type. This is intended for viewing files downloaded to the device.

Social

Rather than requiring developers to create Twitter and Facebook integration from scratch, Apple includes a framework for these popular social networking sites. Using this framework, you can write applications that access Twitter and Facebook without needing to manage account information or understand their proprietary network protocols.

StoreKit

The StoreKit framework enables developers to create in-application transactions for purchasing content without exiting the software. All interactions take place through the App Store, so no financial data is requested or transmitted through the StoreKit methods.

System Configuration

Use the System Configuration framework to determine the current state of a device’s network configuration—what network it is connected to (if any) and what other devices are reachable.

The Core OS Layer

The Core OS layer, as you’d expect, is made up of the lowest-level services in the iOS. These features include threads, complex math, hardware accessories, and cryptography. You should only need to access these frameworks in rare circumstances.

Accelerate

The Accelerate framework simplifies complete calculations and large-number manipulation. This includes digital signal processing capabilities.

Core Bluetooth

The Core Bluetooth framework provides connectivity for low-energy Bluetooth devices. This is a unique class of Bluetooth peripheral that can communicate with extremely low power requirements.

External Accessory

The External Accessory framework is used to develop interfaces to accessories connected via the dock connector or Bluetooth.

Local Authentication

The Local Authentication framework provides the ability to authenticate users via passphrases or the Touch ID sensor.

Security

The Security framework provides functions for performing cryptographic functions (encrypting/decrypting data). This includes interacting with the iOS keychain to add, delete, and modify items.

System

The System framework gives developers access to a subset of the typical tools they would find in an unrestricted UNIX development environment.

Tracing the iOS Application Life Cycle

To help you get a sense for where your “work” in developing an iOS application fits in, it helps to look at the application life cycle. Figure 4.2 shows Apple’s simplified diagram of the life cycle.

Image

FIGURE 4.2 The (simplified) life cycle of a typical iOS application.

Let’s try to put some context around what you’re looking at, starting on the left side of the diagram. As you’ve learned, UIKit is a component of the Cocoa Touch that provides much of the foundation of iOS applications: UI management, event management, and overall application execution management. When you create an application, UIKit handles the setup of the application object via the UIApplicationMain functions, neither of which you should need to touch.

Once the application is started, an event loop begins. This loop receives the events such as screen touches, and then hands them off to your own methods. The loop continues until the application is asked to move to the background (usually through the user pressing the Home button).

Your code comes into play on the right side of the diagram. Xcode automatically sets up your iOS projects to include an application delegate class. This class can implement the methods application:willFinishLaunchingWithOptions, application:didFinishLaunchingWithOptions, and applicationDidEnterBackground (among others) so that your program can execute its own custom code when the application launches and when it is suspended by pressing the Home button.


Wait a Second! When Does My Application Stop Running?

To support this process, the application delegate provides the method applicationDidEnterBackground, which is called when the application enters the background. This method should be used by your code to store any information that the application needs, in case it is terminated while it is the background (either by iOS cleaning up resources or by the user manually terminating it in the task manager). There are even more methods available for handling what happens when a suspended application becomes active again, but we won’t concern ourselves with that until much later.

After an application finishes launching, the delegate object typically creates a view controller object and view and adds them to the iOS “window.” You learn more about these concepts in the next hour, but for now, think of a view as what is being displayed on the device’s screen and the view controller as an object that can be programmed to respond when it receives an event notification (such as touching a button) from the event loop.


The majority of your work will take place within the view controller. You’ll receive events from the Cocoa Touch interface and react to them by writing Swift code that manipulates other objects within the view. Of course, things can get a bit more complex than a single view and a single view controller, but the same basic approach can be applied in most cases.

Now that you have a better picture of the iOS service layers and application life cycle, let’s take a look at some of the classes that you’ll be seeing throughout this book.

Cocoa Fundamentals

Thousands of classes are available in the iOS software development kit (SDK), but most of your applications will be using a small set of classes to implement 90% of their features. To familiarize you with the classes and their purposes, let’s review some of the names you’re going to be seeing very, very often over the next few hours. Before we begin, keep these few key points in mind:

Image Apple sets up much of the structure of your application for you in Xcode. Therefore, even though you need some of these classes, you won’t have to lift a finger to use them. Just create a new Xcode project and they’re added for you.

Image You’ll be adding instances of many of these objects to your projects just by dragging icons in Xcode’s IB. Again, no coding needed!

Image When a class is used, I tell you why it is needed, what it does, and how it is used in the project. I don’t want you to have to jump around digging for references in the book, so focus on the concepts, not memorization.

Image In the last section of this hour’s lesson, you learn about the Apple documentation tool. This will help you find all the class, variable, and method information that you could ever hope for. If it’s gritty details you want, you’ll have them at your fingertips.

Core Application Classes

When you create a new application with even the most basic user interaction, you’ll be taking advantage of a collection of common core classes. Many of these you won’t be touching, but they still perform an important role. Let’s review several of these classes now.

The Application Object (UIApplication)

Every iOS application implements a subclass of UIApplication. This class handles events, such as notification of when an application has finished loading, as well as application configuration, such as controlling the status bar and setting badges (the little red numbers that can appear on application icons). You won’t need to create this yourself; just be aware it exists.

Window Objects (UIWindow)

The UIWindow class provides a container for the management and display of views. In iOS-speak, a view is more like a typical desktop application “window,” whereas an instance of UIWindow is just a container that holds the view. You use only a single UIWindow instance in this book, and it is created automatically in the project templates that Xcode provides for us.

Views (UIView)

The UIView class defines a rectangular area and manages all the onscreen display within that region—what we will refer to as a view. Most of your applications will start by adding a view to an instance of UIWindow.

Views can be nested to form a hierarchy; they rarely exist as a single object. A top-level view, for example, may contain a button and field. These controls would be referred to as subviews and the containing view as the superview. Multiple levels of views can be nested, creating a complex hierarchy of subviews and superviews. You’ll be creating almost all of your views visually in Xcode, so don’t worry: Complex doesn’t mean difficult.

Responders (UIResponder)

The UIResponder class provides a means for classes that inherit from it to respond to the touch events produced by iOS. UIControl, the superclass for nearly all onscreen controls, inherits from UIView and, subsequently, from UIResponder. An instance of UIResponder is just called a responder.

Because multiple objects could potentially respond to an event, iOS passes events up what is referred to as a chain of responders. The responder instance that can handle the event is called the first responder. When you’re editing a field, for example, the field has first responder status because it is actively handling user input. When you leave the field, it “resigns” first responder status. For most of your iOS development work, you won’t be directly managing responders in code.

Onscreen Controls (UIControl)

The UIControl class inherits from UIView and is used as the superclass for almost all onscreen controls, such as buttons, fields, and sliders. This class is responsible for handling the triggering of actions based on touch events, such as “pressing” a button.

As you’ll learn in the next hour, a button defines a handful of events that you can respond to; IB enables you to tie those events to actions that you’ve coded. UIControl is responsible for implementing this behavior behind the scenes.

View Controllers (UIViewController)

You use the UIViewController class in almost all the application projects throughout this book to manage the contents of your views. You use a UIViewController subclass, for example, to determine what to do when a user taps a button. Make a sound? Display an image? However you choose to react, the code you use to carry out your action will be implemented as part of a view controller instance. You’ll learn much more about view controllers over the next two hours.

Data Type Classes

An object can potentially hold data. In fact, most of the classes we’ll be using contain a number of variable properties that store information about an object. There are, however, a set of Foundation classes that you use throughout this book for the sole purpose of storing and manipulating information.

There are two types of data types that you’ll encounter: those that are bridged with Swift and those that aren’t.

Bridged Data Types

iOS development has traditionally relied on Objective-C. In Objective-C, the primitive data types like Integers, Strings, and so on were tied to the C-language underpinnings and had very little functionality. In other words, to program useful applications, Apple needed to implement better versions of these common data types within custom classes.

With Swift, this is no longer necessary. Apple’s implementation of Swift has robust primitive data types that don’t rely on a 40-year-old language. This is both good and bad. It means that we can do a lot in Swift without worrying about creating instances of several data classes. Unfortunately, quite a bit of Cocoa still relies on using these legacy classes as arguments to methods, return data types, and so on; so, they still need to exist.

To make our developer lives easier, Apple has bridged the common Swift and Cocoa data types. This means that while we may work with data types we define in Swift, behind the scenes that are automatically translated to and from Cocoa objects. For the most part, this works well. Sometimes, however, we must still declare an instance of the original Cocoa data class, or use conversion functions or casting to covert between them.

The Cocoa classes and their Swift counterparts are as follows:

Strings (NSString/NSMutableString)

Arrays (NSArray/NSMutableArray)

Dictionaries (NSDictionary/NSMutableDictionary)

Integers/Floating-Point/Booleans (NSNumber/NSDecimalNumber)

When we work through projects over the next 20 hours, we’ll make every effort to use the Swift primitive types—but sometimes you’ll still see these Cocoa classes come into play.

Nonbridged Data Types

Data classes that aren’t bridged aren’t more difficult to work with, they just require a bit more setup in order to use them. Let’s take a look at two Cocoa classes we’ll be using later in the book that implement unique types of data.

Dates (NSDate)

If you’ve ever tried to work with a date manually (interpreting a date string in a program, or even just doing date arithmetic by hand), you know it can be a great cause of headaches. How many days were there in September? Was this a leap year? And so on. The NSDate class provides a convenient way to work with dates as an object.

For example, assume you have a user-provided date (userDate) and you want to use it for a calculation, but only if it is earlier than the current date, in which case, you want to use that date. Typically, this would be a bunch of nasty comparisons and assignments. With NSDate, you would create a date object with the current date in it (provided automatically when the object is initialized):

let myDate: NSDate = NSDate()

And then grab the earlier of the two dates using the earlierDate method:

myDate.earlierDate(userDate)

Obviously, you can perform many other operations, but you can avoid much of the ugliness of data and time manipulation using NSDate objects.

URLs (NSURL)

URLs are certainly a different type of data from what we’re accustomed to thinking about, but on an Internet-connected device like the iPhone and iPad, you’ll find that the ability to manipulate URLs comes in handy. The NSURL class enables you to manage URLs with ease. For example, suppose that you have the URL http://www.teachyourselfios.com/index.html and want to get just the machine name out of the string. You could create an NSURL object:

let myURL: NSURL = NSURL(string:"http://www.teachyourselfios.com/index.html")!

Then use the host variable property to automatically parse the URL and return the text “www.teachyourselfios.com”:

myURL.host

No need to search through the string and figure out the different parts of the URL—Cocoa does it for us. As you can see, nonbridged data types can be useful, and there are dozens more that you can take advantage of during your development.

Interface Classes

Part of what makes iOS Devices so much fun to use are the onscreen touch interfaces that you can create. As we explore Xcode’s IB in the next hour, you’ll get your first hands-on experience with some of these interface classes. Something to keep in mind as you read through this section is that many UI objects can take on very different visual appearances based on how they are configured—so there is quite a bit of flexibility in your presentation.

Labels (UILabel)

You’ll be adding labels to your applications both to present static text onscreen (as a typical label) and as a controllable block of text that can be changed as needed by your program (see Figure 4.3).

Image

FIGURE 4.3 Labels add text to your application views.

Buttons (UIButton)

Buttons are one of the simplest user input methods that you’ll be using. Buttons can respond to a variety of touch events and give your users an easy way to make onscreen choices. Buttons are, by default, borderless, relying on their size, color, and location to make them an obvious control (see Figure 4.4).

Image

FIGURE 4.4 Buttons provide a simple form of user input/interaction.

Switches (UISwitch)

A switch object can be used to collect “on” and “off” responses from a user. It is displayed as a simple toggle and is often used to activate or deactivate application features (see Figure 4.5).

Image

FIGURE 4.5 A switch moves between on and off states.

Segmented Control (UISegmentedControl)

A segmented control creates an elongated touchable bar with multiple named selections (Category 1, Category 2, and so on). Touching a selection activates it and can trigger your application to perform an action, such as updating the screen to hide or show other controls (see Figure 4.6).

Image

FIGURE 4.6 Segmented controls can be used to choose one item out of a set and react accordingly.

Sliders (UISlider)

A slider provides the user with a draggable bobble for the purpose of choosing a value from across a range. Sliders, for example, are used to control volume, screen brightness, and other inputs that should be presented in an “analog” fashion (see Figure 4.7).

Image

FIGURE 4.7 Sliders offer a visual means of entering a value within a range.

Steppers (UIStepper)

Similar to a slider is a stepper (UIStepper). Like a slider, a stepper offers a means of inputting a number from a range of values visually (see Figure 4.8). Pushing a side of the control decrements or increments an internal variable property.

Image

FIGURE 4.8 Use a stepper to increment or decrement values.

Text Fields (UITextField/UITextView)

Text fields are used to collect user input through the onscreen (or Bluetooth) keyboard. The UITextField is a single-line field, similar to what you’d see on a web page order form. The UITextView class, on the other hand, creates a larger multiline text entry block for more lengthy compositions (see Figure 4.9).

Image

FIGURE 4.9 Collect user input through text fields.

Pickers (UIDatePicker/UIPicker)

A picker is an interesting interface element that vaguely resembles a slot machine display. By letting the user change each segment on the wheel, it can be used to enter a combination of several different values. Apple has implemented one complete picker for you: the UIDatePicker class. With this object, a user can quickly enter dates and times. You can also implement your own arbitrary pickers with the UIPicker class (see Figure 4.10).

Image

FIGURE 4.10 Pickers enable users to choose a combination of several options.

Popovers (UIPopoverPresentationController)

Popovers are both a UI element and a means of displaying other UI elements. They allow you to display a view on top of any other view for the purpose of making a choice. The iPad’s Safari browser, for example, uses a popover to present the user with a list of bookmarks to choose from, as shown in Figure 4.11.

Image

FIGURE 4.11 Popovers present information on top of other views.

Most often used on the iPad, Apple has made it possible to use popovers on iPhones as well. We’ll use popovers often in the second half of this book.

These are only a sampling of the classes that you can use in your applications. We explore these and many others in the hours to come.

Exploring the iOS Frameworks with Xcode

So far in this hour, you’ve learned about dozens of frameworks and classes. Each framework could be made up of dozens of additional classes, and each class with hundreds of methods, and so on. In other words, there’s a ridiculous amount of information available about the iOS frameworks.

One of the most efficient ways to learn more is to pick an object or framework you’re interested in and then turn to the Xcode documentation system. Xcode provides an interface to the immense Apple development library in both a searchable browser-like interface (even with video tutorials!) and a context-sensitive Research Assistant. Let’s take a look at both of these features now so that you can start using them immediately.

Xcode Documentation

Xcode is capable of connecting to the Internet and retrieving documentation on-the-fly, but it’s much easier (and faster) to keep a copy of the documentation relevant to your development stored on your Mac. Let’s start our look at the documentation system by making sure we have copies of the documents we want.

Setting Up Documentation Downloads

The Xcode documentation system is kept up-to-date by receiving feeds of document sets from Apple. Document sets are broad categories of documents that cover development for specific OS X versions, Xcode itself, and the iOS releases. To ensure that you have the latest and greatest iOS and Xcode docs stored locally, follow these steps:

1. Open the Xcode Preferences (Xcode, Preferences from the menu bar).

2. Click the Downloads icon on the preference window toolbar.

3. Make sure Check For and Install Updates Automatically is checked.

4. Click the download icon beside each documentation set that you want to retrieve, as shown in Figure 4.12.

Image

FIGURE 4.12 Download a copy of the documentation you need, and automatically keep it up-to-date.

5. Close the Xcode preferences when finished.

Documentation sets take up a surprising amount of room, so if you’re space conscious, only download the sets you need. Now you’re ready to read.


Tip

You can force a manual update of the documentation using the Check and Install Now button.


Searching Documentation

To open the Xcode documentation application, choose Help, Documentation and API Reference from the menu bar. The help system will launch, with a very browser-like appearance. Begin typing a topic of interest into the search field, and, as you type, a list of results appear, as shown in Figure 4.13.

Image

FIGURE 4.13 Search through the available documentation for topics you are interested in.

The results are divided into categories:

Image API Reference: Documents that describe the technical details of a feature, such as the methods and variable properties a class makes available.

Image SDK Guides: Tutorial-like documentation that takes a more high-level view of a feature and describes how it could/should be used.

Image Sample Code: Xcode projects that you can download and use to see a feature demonstrated.

Clicking a result in the list will take you directly to the document you selected. Alternatively, you can click the Show All Results entry to see all possible matches for your search term.


Tip

You can fine-tune your search criteria by clicking the magnifying glass located within the search field. This displays a pop-up menu with selections for limiting your search to specific document sets.


Browsing Documentation

In addition to searching for help, you can also browse all the available documents within your document sets, including online video and sample code. To do this, follow these steps:

1. Click the disclosure arrow in the toolbar if a sidebar isn’t already available. A sidebar will appear in the window.

2. Click the documentation set icon (books on a shelf) to see all the available resources.

3. Drill down into the docs until you find what you’re interested in, as demonstrated in Figure 4.14.

Image

FIGURE 4.14 Explore all the available Xcode documentation resources.

Navigating Documents

When you’ve arrived at a document that you’re interested in, regardless of whether you searched or browsed to find it, you can read and navigate within the document using the blue links. You can also move forward and backward between documents using the arrow buttons located above the content.

If you’re familiar with tabbed browsing, you can choose View, Show Tab Bar. Tabs are added by clicking the + icon at the far right of the tab bar. Command-clicking a link automatically opens it in a new tab, similar to Safari.

To speed up navigation within a document, you can click the table of contents icon in the toolbar to show a TOC (if available) for the document you are currently viewing, as demonstrated in Figure 4.15. Clicking an entry within the TOC jumps to the appropriate location within the document.

Image

FIGURE 4.15 Display the TOC for the current document.

If you find a particularly interesting piece of information, you can bookmark it. To create a bookmark, you use the Share Sheet in the toolbar or simply click the Bookmark icon beside the content that interests you.

To access all your documentation bookmarks, make sure that the sidebar is visible, and then click the bookmark icon, as shown in Figure 4.16.

Image

FIGURE 4.16 Keep track of your favorite help resources.

Quick Help

One of the easiest and fastest ways to get help while coding is through the Xcode Quick Help assistant. To open the assistant, hold down Option and click a symbol in Xcode (for example, a class name or method name) or choose Help, Quick Help. A small window opens with basic information about the symbol, as well as links to other documentation resources.

Using Quick Help

Consider the following line that initializes an NSDate object with a date in the far future (yes, such a feature does exist!):

let myDate: NSDate = NSDate.distantFuture() as NSDate

In this example, there is a class (NSDate) and a method (distantFuture()). To get information about the distantFuture method, hold down Option, and then click it within the code. The Quick Help popover appears, as shown in Figure 4.17. (Notice that the NSDate method returns an object with the type AnyObject—that’s why we have to force it to be considered an NSDate with the as NSDate syntax.)

Image

FIGURE 4.17 Quick Help brings reference information to your code editor.

Click any of the hyperlinks in Quick Help results to jump to a specific piece of documentation or code.


Note

You can tell when you’re hovering over an item that you can click for Quick Help because it will be displayed with a blue dashed underline in the Xcode editor and your mouse cursor will change to show a question mark (?).


Activating the Quick Help Inspector

If you find Quick Help useful and wish you could access it even faster, you’re in luck. The Quick Help Inspector can be used to display help information all the time. Xcode actually displays context-aware help for whatever you’re typing, as you type it.

To display the Quick Help Inspector, open the utility area of the Xcode window using the third (rightmost) View button. Next, click the show Quick Help Inspector icon (a question mark in a circle), located at the top of the utility area, as shown in Figure 4.18. Quick Help automatically displays a reference for whatever code your text-entry cursor is located in.

Image

FIGURE 4.18 Open the Quick Help Inspector for always-on context-aware help.

Interpreting Quick Help Results

Quick Help displays context-sensitive information related to your code in up to eight different sections. What you see depends on the type of symbol (code) you have selected. A variable property, for example, doesn’t have a return type, but a class method does:

Image Declaration: The structure of a method or definition of a data type

Image Description: A few sentences describing the feature that the class, method, or other symbol provides

Image Parameters: The required or option information that can be provided to a method

Image Returns: What information will be returned by a method when it completes

Image Availability: The versions of the operating system where the feature is available

Image Declared In: The file that defines the selected symbol

Image Reference: The official reference documentation for the system

Image Related: Other methods within the same class as your selected method

Image Guides: Additional tutorial documentation that references the selected symbol

Image Sample Code: Sample code files that include examples of class/method/variable use

Quick Help simplifies the process of finding the right method to use with an object. Instead of trying to memorize dozens of instance methods, you can learn the basics and let Quick Help act as an on-demand reference of all of an object’s exposed methods.


Note: Help Yourself!

In the last hour, you learned how to use Markdown syntax-based comments to document your application methods. If you’ve done this, you’ll see your pretty comments rendered in the Quick Help panel when you click a documented method.


Further Exploration

To say that Cocoa Touch is big is an understatement. Every year, Apple releases a major update of iOS and adds thousands of new classes and methods. I try to cover the highlights in this book, but there is much more to explore. To get a taste for the number of frameworks and classes available, I recommend starting with the iOS Technology Overview document, and work through the items under the each layer. This will show you what functionality is built in to the OS and let you focus on the topics that are important to your individual development efforts.

Summary

In this hour, you explored the layers that make up the iOS: Cocoa Touch, Media, Core Services, and Core OS. You learned the structure of a basic application: what objects it uses and how iOS manages the application life cycle. We also reviewed the common classes that you’ll encounter as you begin to work with Cocoa, including data types and UI controls.

To give you the tools you need to find class and method references on your own, this hour introduced you to two features in Xcode. The first, the Xcode documentation window, offers a browser-like interface to the complete iOS documentation. The second, Quick Help, finds help for the class or method you are working with, automatically, as you type. Ultimately, it will be these tools that help you dive deeper into the Apple development environment.

Q&A

Q. Why are the operating system services layered? Doesn’t that add complexity?

A. Using the upper-level frameworks reduces the complexity of your code. By providing multiple levels of abstraction, Apple has given developers the tools they need to easily use iOS features and the flexibility to highly customize their application’s behavior by using lower-level services more closely tied to the OS.

Q. What do I do if I can’t find an interface object I want?

A. Chances are, if you’re writing a “normal” iOS application, Apple has provided a UI class to fill your need. If you find that you’d like to do things differently, you can always subclass an existing control and modify its behavior as you see fit—or create a completely new control.

Workshop

Quiz

1. All applications inherit from which of the following classes?

a. UISoftware

b. UIRunLoop

c. UIObject

d. UIApplication

2. The class file containing the methods required for starting, stopping, and pausing an application is usually which of the following?

a. AppDelegate.swift

b. App.swift

c. Delegate.swift

d. ApplicationDelegate.swift

3. To access Quick Help, hold down _____ while clicking a symbol you want to view.

a. Control

b. Option+Command

c. Option

d. Command

4. A ______ object provides a draggable interface for inputting a value from a range of numbers.

a. UISlider

b. UITextView

c. UIButton

d. UIDraggable

5. Strings and Arrays are examples of Swift data types that are _____ with their Cocoa class counterparts.

a. spanned

b. chained

c. connected

d. bridged

6. Which object contains provides a container for the presentation and management of UIView objects?

a. UIHolder

b. UIWindow

c. UIDesktop

d. UISetup

7. The NS you may encounter in some Cocoa Touch classes is a reference to which platform?

a. NeXTStep

b. OpenStep

c. NixStep

d. NeXTSoftware

8. The class responsible for managing the content of your views is generically known as a what?

a. View Manager

b. UI Manager

c. View Controller

d. Control Manager

9. Much of the technology in the Cocoa Touch classes can be traced back to its origins almost _____ years ago.

a. 30

b. 10

c. 15

d. 50

10. The combination of files and resources needed to implement a piece of functionality is known as a what?

a. Target

b. Class

c. Library

d. Framework

Answers

1. D. All applications you create will inherit from the UIApplication class.

2. A. To control what happens during the launch, termination, and backgrounding of an application, you will likely add code to the AppDelegate.swift file.

3. C. Hold down Option and click a symbol to view the Quick Help for that element.

4. A. The UISlider object creates a draggable interface element that is used to enter a value from a range of numbers.

5. D. Swift data types that are transparently translated to and from Cocoa classes are known as bridged. The String and Array data types are both bridged.

6. B. A UIWindow object acts as a container for the views displayed by your application.

7. A. The NS in some Cocoa Touch class names is a direct reference to the platforms origins in NeXTStep.

8. C. View controllers provide the glue between your interface and the logic implemented within your application.

9. A. The NeXTStep platform, which served as the basis for iOS and Cocoa Touch, is almost 30 years old.

10. D. A framework is the combination of all the code and resources (images, sounds, and so on) required to implement a specific piece of functionality in an application.

Activities

1. Using the Apple Xcode Documentation utility, explore the NSDate class and methods. Identify the methods you’d use to set a date, create a date from a string, and perform common arithmetic functions on a date object.

2. Open Xcode and create a new, empty application. Expand the main code group and click the file named AppDelegate.swift. When the contents of the file appear, open Quick Help by holding Option and clicking inside the class name UIApplication. Review the results. Try clicking other symbols in the Xcode class file and see what happens.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.55.151