Web Development
for the iPhone
Volume Number: 24 (2008)
Issue Number: 06
Column Tag: iPhone
Web Development
for the iPhone
by Rich Warren
Why Web Development?
Let's start with the obvious question. The iPhone SDK gives us the ability to make native applications. Why should anyone bother writing web apps anymore?
Well, web applications have a few advantages over their native counterparts. For example, you don't need to install anything on the iPhone. The application and all its data live on the server. I don't know about you, but my iPhone usually stays around 90% filled. At least for the foreseeable future, disk space on phones will remain at a premium.
Having the data on the server also makes it easier to collaborate with others. Instead of emailing documents back and forth, everyone just logs in and works online. Similarly, web applications enable social networking and wisdom-of-the-crowd applications.
Having the application on the server also makes it easier to push out updates and bug fixes. Your users don't need to download and install the updates. You just change the code on the server. Everyone is updated automatically.
For its part, the iPhone looks like a desirable market for web applications. The iPhone has near-ubiquitous web access. You are not tethered to a LAN or wireless hotspots. Additionally, most people keep their phones with them almost all the time.
Also, the iPhone provides an easy-to-target platform. We know the screen size and resolution. We know the browser. We don't need to build and test against dozens of different hardware and software combinations. At least, not yet.
While iPhones still represent a small fraction of the total web trafficit is a growing percentage. If you have an existing web site or web application, you may want to target iPhone users by building a web interface especially for them.
Finally, Apple must approve all native applications before they can be sold on iTunes. Web applications do not require approval. All you need is a little server space, and a willingness to hack HTML. This gives you more freedom in how you market and sell your software. For example, you can play around with different pricing models, anything from begging for donations to recurring subscription fees. As an added bonus, you don't have to share the proceeds with anyone.
Throughout the rest of this article, we will look at tips and tricks for developing web sites for the iPhone. Apple has identified three typical development scenarios: compatible, optimized and application. The article will follow this structure. We will start by discussing how you can ensure your web pages are compatible with the iPhone. We will then look at optimizing a web page to provide the best iPhone experience. Finally, we will talk about building iPhone-specific web applications.
Compatible
Basically you should use established web standards, and make the web site compatible with Safari 3. Currently, Apple recommends the following:
- HTML 4.01 or XHTML 1.0
- CSS 2.1 and partial CSS3
- JavaScript (ECMAScript 3)
- Ajax (including XMLHTTPRequest)
- If it works on Safari 3, it will work on the iPhone.
- Unless it doesn't.
While it's true that the iPhone uses Safari 3, the iPhone version is not exactly the same as the desktop. They are pretty close, and you can (and probably should) use the desktop version of Safari for development and initial testing. However, you will eventually find a few, rather important differences.
For example, the iPhone sets strict limits on resources. You can only open 8 pages (the equivalent of 8 open windows). Any downloaded resource (not including streamed-media) must be less than 10 MB. And, all JavaScript must take less than 5 seconds to execute.
There's no mouse cursor. You don't really have windows or scroll bars, and pop-up windows are blocked by default. You cannot print from the iPhone, and you cannot access the file system (that means no uploads or downloads).
Additionally, Safari on the iPhone does not support the following:
- Java Applets
- Flash
- SVG
- XSLT
- Plug-ins
- Custom x.509 certificates
- WML
- Mouse-over events
- Hover styles
- Tool Tips
- window.showModalDialog()
Fair enough, but what does it support? The iPhone can view (but not edit) PDFs, Word documents, Excel documents and text files. We can also use the <canvas> tag for vector animation. Canvas allows us to define a drawable area on the web page. It was originally developed by Apple for the Web Kit, and has been used in many Dashboard widgets. Recently, several other browsers have added canvas support, including FireFox and Opera. For more information, check out the Web Kit DOM Programming Topics: Using the Canvas at http://developer.apple.com.
As an iPod, we expect the iPhone to supports a wide range of media. Audio is rather lenient. It supports several different formats, including AAC, MP3, AIFF and WAVE. However, creating video for the iPhone requires a bit more thought.
The phone has a 480 x 320 screen. Users can toggle between full screen mode (where the image is centered and cropped) and letterbox mode, where the image is padded as necessary. Apple recommends scaling your video so that it fits within a 480 x 360 rectangle, while still maintaining the original aspect ratio.
The iPhone supports .mov, .mp4, .m4v, and .3gp video files. It also supports the following compression standards:
H.264 Baseline Profile Level 3.0, up to 640 x 480 at 30 fps (B frames are not supported).
MPEG-4 Part 2 (simple profile).
AAC-LC audio, up to 48 kHz.
Detailed instructions for creating and embedding video can be found in the Safari Web Content Guide for iPhone: Creating Video at http://developer.apple.com; however, here's the quick and dirty version.
While you can set the video encoding options by hand, it's much simpler to use an application with iPhone presets. The easiest options are QuickTime Pro 7.2.1 and iMovie '08. Both allow you to automatically export videos that are optimized for the iPhone. These presets provide two different options, a lower quality that is suitable for watching over an EDGE connection, and a higher quality for wireless access.
You need to export a version for each format you wish to support. You probably want at least iPhone Edge, iPhone wireless and one or more desktop versions.
But, now that we have three or more copies of the same video, how do we host them? Obviously we could offer a link for each version, and just let the users decide. But, that's just asking for trouble. Sooner or later, someone will pick the wrong version, and then post a blog entry about how your site sucks.
Fortunately, there's a better wayQuickTime reference movies. Basically a reference movie is a collection URLs, each with a series of tests. QuickTime automatically checks the capabilities of the connected device and the network speed. It then selects the best movie based on these tests.
QuickTime Pro 7.2.1 automatically creates reference movies when you export web content. Select File > Export for Web. In the dialog box, provide a name and location for your movie. Make sure all three versions (iPhone, iPhone (cellular) and Desktop) are selected. Choose the desired poster image option, then export. QuickTime will automatically create optimized versions of the video for each selected format, a reference movie, a poster image and a ReadMe.html file for your videos.
iMovie '08 only exports one format at a time. For these, export all the versions you wish to use. Then manually build the reference movie using the MakeRefMovie utility. You can download this from http://developer.apple.com/quicktime/quicktimeintro/tools/.
Note: you may want to use MakeRefMovie, even if you have QuickTime Pro on your system. MakeRefMovie gives finer grain control over the tests. You can set the desired network speed, the language, the CPU speed and more. You can also explicitly set the priority for each version in the reference movie. Finally, you can mark versions as iPhone only.
Finally, to actually host any media files, you must configure your server to use byte-range requests. The iPhone uses these requests for random access of media files. Fortunately, most HTTP 1.1 servers already support byte-range requests, so you should be OK. Just keep this in mind, if your video or audio doesn't work.
For the complete list of supported audio and video, check out the Safari Web Content Guide for iPhone: Use Supported Rich Media MIME Types page at http://developer.apple.com.
Optimized
Optimized web sites are specifically designed to work with the iPhone. They must still consider all the compatibility issues mentioned earlier, but now we custom build each web page for the iPhone's screen. The layout takes advantage of the iPhone's shape and size, while user interface elements make touch-based interactions easy. And, the sites focus on just those features that users really want to access on the run.
Apple makes the following recommendations for text:
- Use a 17px to 22px fonts.
- Use bold for emphasis and to delineate lists, show hierarchy or sort order.
- Make labels as succinct as possible. They should start with a capital letter. Do not end with a colon.
- Left align text, especially in lists.
- Avoid using underlines in links. It can make the text appear crowded.
Remember, we are working with a very small size, and potentially over a very slow network. We don't want to send more bits over the air than necessary. In general, images should be reduced to fit on the screen. If you want to provide a larger image (so the user can zoom and pan over them), you can create a link from the smaller placeholder.
Controls, on the other hand, need to be big enough to touch easily. I would recommend making the active area at least 40 x 40 pixels.
And, remember, a lot of the screen may be taken up by the Safari's controls. The size of various built in components are listed below:
Best-case scenario, you've got the iPhone portrait with only the status bar and button bar showing. This gives you a maximum of 320 x 416 px. If the keyboard is displayed, the screen space drops to 320 x 156 px. Landscape, you would have 480 x 268 px and 480 x 44 px respectively. Plan accordingly!
Also, you may have noticed that the iPhone has a somewhat unique user interface. We've already mentioned that there's no mouse. No mouse means no mouse pointer, and this means you cannot use hover events in your page.
We don't have scroll bars. While the iPhone's flick scroll is fine for short documents, flipping to the 400th page in a PDF gets old fast. The lack of scroll bars also means the users may not realize that there is additional information off the screen. So, you may want to break things up into screen-sized chunks.
Additionally, we don't have a keyboard. Not really. Don't get me wrong, the iPhone's virtual keyboard is nice, but it's no replacement for the real thing. Typing on the phone can be slow and error-prone. Try to limit the amount of information that users must type. If possible use drop down menus, or remember their information and reuse it the next time they visit your site.
Finally, the users often treat the iPhone differently than a desktop browser. With the iPhone, the Internet is available almost anywhere, but it might be painfully slow. So, focus on a few key featuresthings users might want to access quickly while running around town. Also, keep the pages as light as possible to improve load times.
OK, you've got the basic layout down, but how do you serve it? You have two options. The easiest approach is to build an entirely separate set of pages that are optimized for the iPhone, and have them accessible through a special URL. Of course, when I say simple, I mean the setup is simple. You still need to ensure that all iPhone visitors know about your special URLs. Good luck with that.
Alternatively, you can make your site automatically serve iPhone content to iPhones, and desktop content to desktops. We'll look at two methods for doing this. First, we will automatically send iPhone-only CSS style sheets to the iPhone. Then, we'll scan the user agent string and determine what type of browser we're dealing with.
iPhone-Specific CSS
Sometimes you can optimize your site by just providing different CSS style sheets for the different browsers. We do this through the media link. Note: however, this is not an exact science. We use the browser's minimum and maximum widths to infer the browser type. However, other mobile devices may have similar sized screens. This may or may not cause problems, depending on the page's content and layout.
The following link will load an iPhone specific style sheet:
<link media="only screen and (max-device-width: 320px)"
href="iphone.css" type="text/css" rel="style-sheet">
The desktop version can be loaded as follows:
<link media="only screen and (min-device-width: 321px)"
href="iphone.css" type="text/css" rel="style-sheet">
You can even combine min-device-width and max-device-width to further restrict the choices.
<link media="only screen and (min-device-width: 320px)
and (max-device-width: 320px)"
href="iphone.css" type="text/css" rel="style-sheet">
Note: even though the iPhone has a 480 px width while in landscape mode, it always loads the CSS style sheet for 320 px wide media. So, you cannot use the media link to distinguish between portrait and landscape mode.
One of the main advantages of working through CSS is that you do not need to write any server-side code. The browser handles everything automatically. However, CSS is limited. You can change the look and feel of the web page, but to really alter the content, you may need something more.
Parsing the User Agent
Many web sites are built using JSP, PHP, Ruby on Rails or some other web-programming platform. All of these can scan the browser's user agent before programmatically building your web page. If the browser is an iPhone or iPod Touch, the application builds an iPhone-specific page. Otherwise it builds a regular page.
In general, parsing the User Agent string (also called "browser sniffing") is frowned upon. It's better to use Object Detection (where you check the browsers capabilities, rather than the browser type). However, when you're working on something as specific as the iPhone, sniffing may make sense. The iPhone is different enough in both its form factor and capabilities, it deserves special treatment.
The iPhone's user agent should appear similar to the following:
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419.3
This can be broken into the following segments:
It is probably simplest to just search the user agent for "iPhone". Of course, the iPod Touch uses a different platform string, (iPod; U; CPU like Mac OS X; en). If you want to support both, you will need to look for both versions. Likewise, if Apple ever releases the mythical PDA or tablet sized touch screen device, it will probably have its own user agent. Now, we start to see why browser sniffing can become a problem.
To Sniff or Not To Sniff
Personally, I like web sites that automatically serve up iPhone specific versions, but that's not a universal preference. The Safari browser does a good job handling most content, and some users feel cheated when they see stripped-down pages. They want the full version with all the bells and whistles.
Therefore, it's usually a good idea to provide easy-to-find links between the iPhone and full versions. If you really want to make the users happy, remember which version they last visited, and give it to them when they return.
Application
Alright, now it's time to build actual web application for the iPhone. Of course, the dividing lines between compatible pages, optimized pages and full-bore web applications is hazy at best. Basically, a web application is just like an optimized page, only more so.
Applications should be even more focused. We often talk about feature creep in desktop applicationsbut a desktop application can afford a bit of bulk. We have more screen space for things like complex toolbars and long menus. Applications on the iPhone do not have this luxury. The best developers strip their applications down to the bone. Bottom line, resist the urge to add features for features sake.
Almost by definition, the application should be interactive, and it needs to respond quickly to the user. That almost certainly means using AJAX for much of the interface.
One of the key differences between a web application and an optimized web page is that the application tries to mimic the look and feel of the other, native iPhone applications. As much as possible, your web application should not feel like just another web page.
For example, iPhone's ability to zoom through a double tap or a pinch is impressivebut it is not used in most native applications. The interface simply fills the screen's width, and only vertical scrolling is allowed.
We can prevent zooming and horizontal scrolling in our web applications by adding the following meta tag to our HTML's header:
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
Now, we want to make the page look like an iPhone application. Fortunately, we don't need to create all the CSS and JavaScript code ourselves. Joe Hewitt has released a small collection of graphical elements, CSS style sheets and JavaScripts that mimic the iPhone's native look and feel. His iUi project can be found at http://code.google.com/p/iui/.
To use iUi, simply link you page to the CSS and JavaScript files. Your web page can contain both hidden and visible elements. Indicate the initially visible elements by setting their selected attribute to true. Use anchor links to navigate between elements. The scripts handle everything else automatically. Here's a quick sample:
Sample iUi Application
This shows a simple, two page iUi application. The iUi framework starts by displaying the home <ul>. JavaScript handles transitions between #home and #next, sliding the pages in from the left or right, as appropriate.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width;
initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<style type="text/css" media="screen">@import "iui/iui.css";</style>
<script type="application/x-javascript" src="iui/iui.js"></script>
<title>My iPhone App</title>
</head>
<body>
<div class="toolbar">
<h1 id="pageTitle">Fake App</h1>
<a id="backButton" class="button" href="#"></a>
<a class="button" href="#next">next</a>
</div>
<ul id="home" title="My List" selected="true">
<li><a href="#next">This is a list</a></li>
<li>It is a really cool list</li>
<li>Just a little short...</li>
</ul>
<div id="next" title="The Second Page" class="panel">
<h2>My Group 1</h2>
<fieldset>
<div class="row">
<label>This is still a list.</label>
</div>
<div class="row">
<label>It is still pretty cool.</label>
</div>
</fieldset>
<h2>My Group 2</h2>
<fieldset>
<div class="row">
<label>But it's a bit more complicated,</label>
</div>
<div class="row">
<label>As you can see...</label>
</div>
</fieldset>
</div>
</body>
</html>
As you can see, the first div creates our toolbar. Initially it has a single button, next. The application starts with the unordered list visible, and both the first item in the list and the next button are linked to the next div.
The next div is not visibly initially. However, it will slide in when either the next button or the first list item are pressed. It displays an iPhone grouped list.
Connecting to Other Applications
Not all web applications are an island. We can leverage some of the native applications through specialized URLs. Specifically, we can access the phone, Mail, Map and YouTube.
Let's start with the simplest. By default, Safari automatically detects phone numbers and converts them into links. The user just clicks the link to call the number.
We can turn off this auto-detection using the following meta tag:
<meta name="format-detection" content="telephone=no">
We can also manually create phone links:
<a href="tel:1-800-123-4567">1-800-123-4567</a>
Accessing the Mail application is almost as easy. Just use the mailto: link. Remember, we can fill in more than just the To: address.
<a href="mailto:john.doe@anonymous.com?cc=jane.doe@anonymous.com&
subject=New%20Application&body=guest%20account">request guest account</a>
We can launch the Map by linking directly to Google maps. This has two formats. The first will place a single pin at the given location. The second will create a route between the source and destination. Both are shown below:
<a href="http://maps.google.com/maps?q=honolulu,+HI">Honolulu</a>
<a href="http://maps.google.com/maps?daddr=waikiki,+HI&saddr=airport
+honolulu,+HI">To Waikiki</a>
We can also launch the YouTube application by creating a link containing the video identifier. This has two equivalent forms:
<a href="http://www.youtube.com/watch?v=Yz1-cPx0cIk">60 Second Keynote</a>
<a href="http://www.youtube.com/v/Yz1-cPx0cIk>60 Second Keynote</a>
Note: however, you cannot embed the video in your page. Embedded YouTube clips require Flash, which is not yet available on the iPhone. If you want to put iPhone compatible videos on your web page or in your web application, you must use one of the links above.
Finally, to give our pages that real application feel, we should create a web clip icon for our application. Icons should be 57 x 57 pixels. Note: Safari will add a glassy overlay to our icon, to help it match the native iPhone icons. So, don't be surprised if it looks a little different.
To set a default icon for the entire site, place a PNG image named "apple-touch-icon.png" at the root directory of your web server. This is similar to setting a site's "favicon.ico" icon.
We can also override the icon for a specific page by adding the following to the page's header:
<link rel="apple-touch-icon" href="/myIcon.png"/>
That's it. Publish your application to a public server, and your application is deployed.
Development Tools
Web development often includes multiple pieces written in different languages. We use HTML for the content, CSS for the layout. We create dynamic content using a programming language (etc PHP, Java, Ruby, Python), and manage interactive bits using JavaScript.
A mistake in any part of the page can create bugs for our application. Unfortunately, this mishmash of techniques and technologies can make it hard to find and fix the problem. Fortunately, we have a number of powerful tools at our fingertips.
iPhone Console
First and foremost, we can turn on the iPhone's debug console. Launch the Settings application. Tap Safari, then scroll down and tap Developer. Once there, we can toggle the Debug Console on and off.
The console will log error messages and development tips for HTML, CSS and JavaScript. We can also explicitly send messages using JavaScript. There are four message levels: log, info, warn and error. However, info is the same as log. It was just provided for backward compatibility.
Sample Console Messages
This shows the four different types of console message. Again, log and info messages are functionally equivalent. They will appear the same on the iPhone.
console.log("this is a log message");
console.info("this is an info message");
console.warn("this is a warning");
console.error("this is an error");
When the console is active, Safari will show a banner over the web page. The banner will either list the number of messages, or simply state No Errors. If you have messages, you can click on the banner to view the complete list. Once in the console window, you can filter the message to see only HTML, CSS or JavaScript.
Note: the banner is only visible when the URL text field is visible. If your application automatically scrolls the URL field off the screen, you will need to scroll back up to find it.
Web Inspector
Web Inspector
Safari also comes complete with a full debugging suite. However, these options are hidden by default. To turn on the Develop menu, enter the following at the command line:
defaults write com.apple.Safari IncludeDebugMenu 1
The Develop menu gives you a number of options. You can open the current page with another browser. You can set your user agent string, letting you mimic other browsers. You can even disable everything from the caches to CSS and JavaScript.
Most importantly, however, you can launch the Web Inspector. The Web Inspector is your own, personal CSI lab for investigating web page problems. It has three main views: Inspector, Error Console and Network Timeline.
The Inspector shows all the resources loaded with this web page. All the html files, CSS sheets, script files, images, whatever. You can look at each one. Images are displayed as they will appear on screen. CSS and scripts show the complete source code. However, the HTML view is by far the coolest.
You can view HTML as either raw source or a DOM tree. The source view provides a nice syntax-highlighted view of the source code, but there's really nothing special here. The true magic comes from the DOM tree.
When you click on an element in the DOM tree, it will highlight the corresponding portion of the web page in Safari. This lets you easily, visually match code to content. The right sidebar also show you the computed or inherited styles for the selected node; the border, margin and padding for the node, and any properties.
Finally, Safari includes a handy shortcut for inspecting particular parts of the page. Right click on any item in the web page, and select Inspect Element. The Web Inspector will automatically open to that node in the DOM tree.
Next we have the Web Inspector's Console view. This displays console messagesjust like the console on the iPhone. Again, useful, but nothing special here.
However, the Network Timeline is a nice touch. This gives us detailed information on how the page loaded: The order in which each resource was downloaded, and the amount of time each resource took. It also displays the total size for each type of resource. Finally, if you click on any row, it will give you detailed information on that particular HTTP request and response.
Network Timeline
The information provided by the Network Timeline could be vital for optimizing web pages for iPhones over the slower Edge network.
Drosera
Drosera
While the other tools are nice, if you are serious about JavaScript, you need to download and install Drosera. Drosera is a JavaScript debugger. It works just like any code debugger. You can view the JavaScript source code, set break points (including conditional break points), and step through and inspect your code.
Drosera can attach to any WebKit application, including Safari. Unfortunately it is not included in OS X, not even in the developer tools. However, it comes bundled with the WebKit nightly builds.
Download the nightly build from http://webkit.org. Then copy both the WebKit and Drosera to your application's folder. You can already attach Drosera to the WebKit. To debug from Safari, just enter the following at the command line:
defaults write com.apple.Safari WebKitScriptDebuggerEnabled -bool true
Open Safari. Open Drosera and attach it to Safari. Now open a web page. Set your breakpoints, then reload the web page.
Unfortunately, Drosera still feels a bit buggy at times. It can lose track of script files, and often fails to show the variables. But, even when it misbehaves, it's a great tool to have in your toolbox.
iPhone Emulators
While you can run iPhone web apps in any Safari 3.0 browser, it's often nice to see it in an emulatorjust to make sure everything looks right.
Fortunately, Apple has provided a great simulator. Currently it is only available as part of the iPhone 2.0 SDK Beta. Just sign up as an iPhone Developer, download the SDK and install it.
Of course, you might have trouble finding the simulator. They've tucked it away at /Developer/Plat-forms/iPhoneSimulator.platform/Developer/Applications/iPhoneSimulator.app. Find it, launch it, love it.
There's really only one, temporary drawback to all this. The simulator uses the new iPhone 2.0 OS. So, you may find some differences between the current version of Safari on the iPhone and the upcoming 2.0 release. Of course, you're testing your application on an actual phone as well, right? So no worries.
Conclusion
Ok, maybe they're not native applications. But, maybe that's not such a bad thing.
The iPhone is a natural target for many web applications. It's like carrying the internet in your pants pocket. I don't know how many times I've used my phone to settle bar bets. Ok, not exactly bar bets, more like coffee house betsbut it helps me swindle the last bite of triple-chocolate chunk cookie from my daughter.
While iPhone's version of Safari handles most web pages, optimized pages and web applications really improve the browsing experience, especially over Edge. Most web sites could benefit from building an iPhone specific interface (I'm looking at you, Wikipedia).
Sure, the iPhones still represent a small percentage of total web trafficbut it's a steadily growing percentage. And, face it, it's a desirable target market. If you can afford to drop $400 on a phone, you probably have a little extra cash for other things as well (that or really gullible parents).
Additionally, we don't need Apple's permission to make and publish our web applications. The web is still freeor at least, reasonably priced. Web applications may not have the full power and crispness of a native application, but they're also not locked down.
Finally, we have a number of excellent tools that will let us create high-quality iPhone-specific web sites.
So, they may not get as much press as the native applications, but web applications still contribute to the iPhone ecosystem. They fill a niche that is not going away anytime soon. And I think that's a good thing.