Chapter 1. Getting Started

If you know HTML, CSS, and JavaScript, you already have what you need to develop your own iPhone apps. With this book, you'll learn how to use these open source web technologies to design and build apps for both the iPhone and iPod Touch. Buy the print book or ebook or purchase the iPhone App.

Before we dive in and start building applications for the iPhone, I’d like to quickly establish the playing field. In this chapter, I’ll define key terms, compare the pros and cons of the two most common development approaches, and present a crash course in the three core web technologies that are used in this book.

Web Apps Versus Native Apps

First, I’ll define what I mean by “web app” and “native app” and consider the pros and cons of each.

What Is a Web App?

To me, a web app is basically a website that is specifically optimized for the iPhone. The site can be anything from a standard small-business brochure site to a mortgage calculator to a daily calorie tracker—the content is irrelevant. The defining characteristics of a web app are that the user interface is built with web-standard technologies, it is available at a URL (public, private, or behind a login), and it is optimized for the specifics of the iPhone. A web app is not installed on the phone, is not available in the iTunes App Store, and is not written with Objective-C.

What Is a Native App?

In contrast, native apps are installed on the iPhone, have access to the hardware (speakers, accelerometer, camera, etc.), and are written with Objective-C. The defining characteristic of a native app, however, is that it’s available in the iTunes App Store—a feature that has captured the imagination of hordes of software entrepreneurs worldwide, myself included.

Pros and Cons

Different applications have different requirements. Some apps are a better fit with web technologies than others. Knowing the pros and cons of each approach will help you make the right decision about which path is appropriate for your situation.

Here are the pros of native app development:

  • Millions of registered credit card owners are one click away.

  • Xcode, Interface Builder, and the Cocoa Touch framework constitute a pretty sweet development environment.

  • You can access all the cool hardware features of the device.

Here are the cons of native app development:

  • You have to pay to become an Apple developer.

  • You are at the mercy of the Apple approval process.

  • You have to develop using Objective-C.

  • You have to develop on a Mac.

  • You can’t release bug fixes in a timely fashion.

  • The development cycle is slow, and the testing cycle is constrained by the App Store’s limitations.

Here are the pros of web app development:

  • Web developers can use their current authoring tools.

  • You can use your current web design and development skills.

  • You are not limited to developing on the Mac OS.

  • Your app will run on any device that has a web browser.

  • You can fix bugs in real time.

  • The development cycle is fast.

Here are the cons of web app development:

  • You cannot access the all cool hardware features of the phone.

  • You have to roll your own payment system if you want to charge for the app.

  • It can be difficult to achieve sophisticated UI effects.

Which Approach Is Right for You?

Here’s where it gets exciting. The always-online nature of the iPhone creates an environment in which the lines between a web app and a native app get blurry. There are even some little-known features of the iPhone that allow you to take a web app offline if you want (see Chapter 6, Going Offline). What’s more, several third-party projects—of which PhoneGap is the most notable—are actively developing solutions that allow web developers to take a web app and package it as a native app for the iPhone and other mobile platforms.

For me, this is the perfect blend. I can write in my native language, release a product as a pure web app (for the iPhone and any other devices that have a modern browser) without going through Apple’s approval process, and use the same codebase to create an enhanced native version that can access the device hardware and potentially be sold in the App Store. And if Apple rejects it? No big deal, because I still have my online version. I can keep working on the native version while customers use the web app.

Web Programming Crash Course

The three main technologies we are going to use to build web apps are HTML, CSS, and JavaScript. I’d like to quickly cover each to make sure we’re all on the same page before plowing into the fancy stuff.

Intro to HTML

When you’re browsing the Web, the pages that you are viewing are just text documents sitting on someone else’s computer. The text in a typical web page is wrapped in HTML tags, which tell your browser about the structure of the document. With this information, the browser can decide how to display the information in a way that makes sense.

Consider the web page snippet shown in Example 1.1, “HTML snippet”. On the first line, the string Hi there! is wrapped in a pair of h1 tags. (Notice that the open tag and the close tag are slightly different: the close tag has a slash as the second character, while the open tag does not.)

Wrapping some text in h1 tags tells the browser that the words enclosed are a heading, which will cause it to be displayed in large bold text on its own line. There are also h2, h3, h4, h5, and h6 heading tags. The lower the number, the more important the header, so text wrapped in an h6 tag will be smaller (i.e., less important-looking) than text wrapped in an h3 tag.

After the h1 tag in Example 1.1, “HTML snippet” are two lines wrapped in p tags. These are called paragraph tags. Browsers will display each paragraph on its own line. If the paragraph is long enough to exceed the width of the browser window, the text will bump down and continue on the next line. In either case, a blank line will be inserted after the paragraph to separate it from the next item on the page.

Example 1.1. HTML snippet

<h1>Hi there!</h1>
<p>Thanks for visiting my web page.</p>
<p>I hope you like it.</p>

You can also put HTML tags inside of other HTML tags. Example 1.2, “Unordered list” shows an unordered list (ul) tag that contains three list items (li). In a browser, this would show up as a bulleted list, with each item on its own line. When you have a tag or tags inside of another tag, the inner tags are called child elements, or children, of the parent tag. So in this example, the lis are children of the ul parent.

Example 1.2. Unordered list

<ul>
    <li>Pizza</li>
    <li>Beer</li>
    <li>Dogs</li>
</ul>

The tags I’ve covered so far are all block tags. The defining characteristic of a block tag is that it is displayed on a line of its own, with no elements to its left or right. That is why headings, paragraphs, and list items progress down the page instead of across it. The opposite of a block tag is an inline tag, which, as the name implies, can appear in a line. The emphasis tag (em) is an example of an inline tag, and it looks like this:

<p>I <em>really</em> hope you like it.</p>

The granddaddy of the inline tags—and arguably the coolest feature of HTML—is the a tag. The a stands for anchor, but I’ll also refer to the tag as a link or hyperlink. Text wrapped in an anchor tag becomes clickable, such that clicking on it causes your browser to load a new HTML page.

In order to tell the browser what new page to load, we have to add what’s called an attribute to the tag. Attributes are named values that are inserted into an open tag. In an anchor tag, you use the href attribute to specify the location of the target page. Here’s a link to Google’s home page:

<a href="http://www.google.com/">Google</a>

That might look like a bit of a jumble if you are not used to reading HTML, but you should be able to pick out the URL for the Google home page. You’ll be seeing a lot of a tags and hrefs throughout the book, so take a minute to get your head around this if it doesn’t make sense at first glance.

Note

There are a couple of things to keep in mind regarding attributes. Different HTML tags allow different attributes. You can add multiple attributes to an open tag by separating them with spaces. You never add attributes to a closing tag. There are hundreds of possible combinations of attributes and tags, but don’t sweat it. We only have to worry about a dozen or so in this book.

The HTML snippet that we’ve been looking at would normally reside in the body section of a complete HTML document. An HTML document is made up of two sections: the head and the body. The body is where you put all the content that you want users to see. The head contains information about the page, most of which is invisible to the user.

The body and head are always wrapped in an html element. Example 1.3, “A proper HTML document” shows the snippet in the context of a proper HTML document. For now the head section contains a title element, which tells the browser what text to display in the title bar of the window.

Example 1.3. A proper HTML document

<html>
    <head>
        <title>My Awesome Page</title>
    </head>
    <body>
        <h1>Hi there!</h1>
        <p>Thanks for visiting my web page.</p>
        <p>I hope you like it.</p>
        <ul>
            <li>Pizza</li>
            <li>Beer</li>
            <li>Dogs</li>
        </ul>
    </body>
</html>

Normally, when you are using your web browser you are viewing pages that are hosted on the Internet. However, browsers are perfectly good at displaying HTML documents that are on your local machine as well. To see what I mean, crack open a text editor and type up Example 1.3, “A proper HTML document”. When you are done, save it to your desktop as test.html and then open it with Safari by either dragging the file onto the Safari application icon or opening Safari and selecting FileOpen File. Double-clicking test.html might work as well, but it could open in your text editor or another browser depending on your settings.

Note

Even if you aren’t running Mac OS X, you should use Safari when testing your iPhone web apps on a desktop web browser, because Safari is the closest desktop browser to the iPhone’s Mobile Safari. Safari for Windows is available from http://www.apple.com/safari/.

Caution

Some text editors are bad for authoring HTML. In particular, you want to avoid editors that support rich text editing, like Microsoft Word or TextEdit. These types of editors can save their files in formats other than plain text, which will break your HTML. If you are in the market for a good text editor, my favorite by far on the Mac is TextMate (http://macromates.com/), and I hear that there is a clone version for Windows called E Text Editor (http://www.e-texteditor.com/). If free is your thing, you can download Text Wrangler for Mac (http://www.barebones.com/products/TextWrangler/) or use the built-in Notepad on Windows.

Intro to CSS

As you’ve seen, browsers render certain HTML elements with distinct styles (headings are large and bold, paragraphs are followed by a blank line, etc.). These styles are very basic and are primarily intended to help the reader understand the structure and meaning of the document.

To go beyond this simple structure-based rendering, you can use Cascading Style Sheets (CSS). CSS is a stylesheet language that is used to define the visual presentation of an HTML document. You can use CSS to define simple things like the text color, size, and style (bold, italic, etc.), or complex things like page layout, gradients, opacity, and much more.

Example 1.4, “A simple CSS rule” shows a CSS rule that instructs the browser to display any text in the body element using the color red. In this example, body is the selector (what is affected by the rule) and the curly braces enclose the declaration (the rule itself). The declaration includes a set of properties and their values. In this example, color is the property, and red is the value of the property.

Example 1.4. A simple CSS rule

body { color: red; }

Property names are predefined in the CSS specification, which means that you can’t just make them up. Each property expects an appropriate value, and there can be lots of appropriate values and value formats for a given property.

For example, you can specify colors with predefined keywords like red, or by using HTML color code notation. This uses a hexadecimal notation: three pairs of hexadecimal digits (0–F) representing (from left to right) Red, Green, and Blue values. Properties that expect measurements can accept values like 10px, 75%, and 1em. Example 1.5, “Some common CSS declarations” shows some common declarations. (The color code shown for background-color corresponds to the CSS “gray”.)

Example 1.5. Some common CSS declarations

body {
    color: red;
    background-color: #808080;
    font-size: 12px;
    font-style: italic;
    font-weight: bold;
    font-family: Arial;
}

Selectors come in a variety of flavors. If you wanted all of your hyperlinks (the a element) to display in italics, you would add the following to your stylesheet:

a { font-style: italic; }

If you wanted to be more specific and only italicize the hyperlinks that were contained somewhere within an h1 tag, you would add the following to your stylesheet:

h1 a { font-style: italic; }

You can also define your own custom selectors by adding id and/or class attributes to your HTML tags. Consider the following HTML snippet:

<h1 class="loud">Hi there!</h1>
<p id="highlight">Thanks for visiting my web page.</p>
<p>I hope you like it.</p>
<ul>
    <li class="loud">Pizza</li>
    <li>Beer</li>
    <li>Dogs</li>
</ul>

If I added .loud { font-style: italic; } to the CSS for this HTML, Hi there! and Pizza would show up italicized because they both have the loud class. The dot in front of the .loud selector is important. It’s how the CSS knows to look for HTML tags with a class of loud. If you omit the dot, the CSS would look for a loud tag, which doesn’t exist in this snippet (or in HTML at all, for that matter).

Applying CSS by id is similar. To add a yellow background fill to the highlight paragraph tag, you’d use this rule:

#highlight { background-color: yellow; }

Here, the # symbol tells the CSS to look for an HTML tag with the id highlight.

To recap, you can opt to select elements by tag name (e.g., body, h1, p), by class name (e.g., .loud, .subtle, .error), or by id (e.g., #highlight, #login, #promo). And you can get more specific by chaining selectors together (e.g., h1 a, body ul .loud).

Note

There are differences between class and id. class attributes should be used when you have more than one item on the page with the same class value. Conversely, id values have to be unique to a page.

When I first learned this, I figured I’d just always use class attributes so I wouldn’t have to worry about whether I was duping an id value. However, selecting elements by id is much faster than selecting them by class, so you can hurt your performance by overusing class selectors.

So now you understand the basics of CSS. But how do you apply a style sheet to an HTML page? It’s actually quite simple. You just link to the stylesheet in the head of the HTML document, as seen in Example 1.6, “Linking to a CSS stylesheet”. The href attribute in this example is a relative path, meaning that it points to a text file named screen.css in the same directory as the HTML page. You can also specify absolute links, such as:

http://example.com/screen.css

Example 1.6. Linking to a CSS stylesheet

<html>
    <head>
        <title>My Awesome Page</title>
        <link rel="stylesheet" href="screen.css" type="text/css" />
    </head>
    <body>
        <h1 class="loud">Hi there!</h1>
        <p id="highlight">Thanks for visiting my web page.</p>
        <p>I hope you like it.</p>
        <ul>
            <li class="loud">Pizza</li>
            <li>Beer</li>
            <li>Dogs</li>
        </ul>
    </body>
</html>

Example 1.7, “A simple stylesheet” shows the contents of screen.css. You should save this file in the same location as the HTML file.

Example 1.7. A simple stylesheet

body {
    font-size: 12px;
    font-weight: bold;
    font-family: Arial;
}        

a { font-style: italic; }
h1 a { font-style: italic; }

.loud { font-style: italic; } 
#highlight { background-color: yellow; }

Note

It’s worth pointing out that it’s possible to link to stylesheets that are hosted on domains other than the one hosting the HTML document. However, it’s considered very rude to link to someone else’s stylesheets without permission, so please only link to your own.

For a quick and thorough crash course in CSS, I highly recommend CSS Pocket Reference by Eric Meyer (O’Reilly). Eric has the last word when it comes to CSS, and this particular book is short enough to read during the typical morning carpool. Unless you are the person driving, in which case it could take considerably longer (did I say “crash” course?).

Intro to JavaScript

At this point you should know how to structure a document with HTML and how to modify its visual presentation with CSS. Now we’ll add some JavaScript to make it do stuff.

JavaScript is a scripting language that can be added to an HTML page to make it more interactive and convenient for the user. For example, you can write some JavaScript that will inspect the values typed in a form to make sure they are valid. Or you can have JavaScript show or hide elements of a page depending on where the user clicks. JavaScript can even contact the web server to execute database changes without refreshing the current web page.

Like any modern scripting language, JavaScript has variables, arrays, objects, and all the typical control structures (if, while, for, and so on). Example 1.8, “Basic JavaScript syntax” shows a snippet of JavaScript that illustrates several core concepts of the language.

Example 1.8. Basic JavaScript syntax

var foods = ['Apples', 'Bananas', 'Oranges']; 1
for (var i in foods) { 2
  if (foods[i] == 'Apples') { 3
    alert(foods[i] + ' are my favorite!'); 4
  } else {
    alert(foods[i] + ' are okay.'); 5
  }
}

Here’s an explanation of what’s happening here:

1

Define an array named foods that contains three elements.

2

Open a for loop that defines a variable named i that will contain the index of each element of the array during the loop.

3

A garden-variety if checks to see if the current element of the array is equal to Apples.

4

This is displayed if the current element of the array is equal to Apples.

5

This is displayed if the current element of the array is not equal to Apples.

Here are some points about JavaScript’s syntax that are worth noting:

  • Statements are terminated with semicolons.

  • Code blocks are enclosed in curly braces.

  • Variables are declared using the var keyword.

  • Array elements can be accessed with square bracket notation.

  • Array keys are assigned beginning at 0.

  • The single equals sign is the assignment operator.

  • The double equals sign is the equivalence logical operator.

  • The plus sign is the string concatenation operator.

For our purposes, the most important feature of JavaScript is that it can interact with the elements of an HTML page (the cool kids call this “manipulating the DOM”). Example 1.9, “Simple OnClick handler” shows a simple bit of JavaScript that changes some text on the page when the user clicks on the h1.

Note

DOM stands for Document Object Model, and in this context it represents the browser’s understanding of an HTML page. You can read more about the Document Object Model here: http://en.wikipedia.org/wiki/Document_Object_Model.

Example 1.9. Simple OnClick handler

<html>
    <head>
        <title>My Awesome Page</title>
        <script type="text/javascript" charset="utf-8"> 1
            function sayHello() { 2
                document.getElementById('foo').innerHTML = 'Hi there!'; 3
            } 4
        </script> 5
    </head>
    <body>
        <h1 id="foo" onclick6="sayHello()">Click me!</h1>
    </body>
</html>

Here’s an explanation:

1

I’ve added a script block to the head of the HTML document.

2

Inside the script block, I’ve defined a single JavaScript function named sayHello().

3

The sayHello() function contains a single statement, which tells the browser to “look through the document for an element that has the id ‘foo’, and set its innerHTML contents to ‘Hi there!.’” The effect of this in the browser is that the text “Click me!” will be replaced with “Hi there!” when the user clicks on the h1 element.

4

End of the sayHello() function.

5

End of the script block.

6

The onclick attribute of the h1 element tells the browser to do something when the user clicks on the h1, namely, to run the sayHello() function.

Back in the bad old days of web development, different browsers had different support for JavaScript. This meant that your code might run in Safari 2 but not in Internet Explorer 6. You had to take great pains to test each browser (and even different versions of the same browser) in order to make sure your code would work for everyone. As the number of browsers and browser versions grew, it became impossible to test and maintain your JavaScript code for every environment. At that time, web programming with JavaScript was hell.

Enter jQuery. jQuery is a relatively small JavaScript library that allows you to write your JavaScript code in a way that will work the same in a wide variety of browsers. What’s more, it greatly simplifies a number of common web development tasks. For these reasons, I use jQuery in most of my web development work, and I’ll be using it for the JavaScript examples in this book. Example 1.10, “jQuery OnClick handler” is a jQuery rewrite of Example 1.9, “Simple OnClick handler”.

Example 1.10. jQuery OnClick handler

<html>
     <head>
        <title>My Awesome Page</title>
        <script type="text/javascript" src="jquery.js"></script> 1
        <script type="text/javascript" charset="utf-8">
             function sayHello() {
                 $('#foo').text('Hi there!'); 2
             }
        </script>
    </head>
    <body>
        <h1 id="foo" onclick="sayHello()">Click me!</h1>
    </body>
</html>

1

Here, I include the jquery.js library. I’ve used a relative path, meaning that the file exists in the same directory as the page that is using it, but I could have included it directly from a variety of places where it’s available.

2

Notice the reduction in the amount of code we need to write to replace the text in the h1 element. This might not seem like a big deal in such a trivial example, but I can assure you that it’s a lifesaver in complex solutions.

We’ll be seeing plenty of real-world jQuery examples later on, so I’m going to leave it at that for the moment.

Note

jQuery downloads, documentation, and tutorials are available at http://jquery.com. To use jQuery, you will need to download it from the website, rename the file you downloaded (such as jquery-1.3.2.min.js) to jquery.js, and put a copy of it in the same directory as your HTML document.

Site last updated on: November 17, 2010 at 10:11:32 AM PST