Ting-Tong | Cowboy Action Town | Tutorials | About Me | Contact

(Just About) Everything you need to know about building an iPhone web app: step-by-step guide with code samples

Introduction
Detecting iPhone traffic & redirection
Setting up your basic page framework
Scaling your page to fit the viewport window
Defining an icon for your web app
Defining a startup splash image
Hiding the address bar
Force minimum screen height with CSS
Styling your content
Margin, padding and background
Text size
Lists
Creating an iPhone-like search box
Form field "Placeholder"
Form field "Autofocus"
Form field "Autocomplete"
Form field "Autocapitalize"
Form field types
Fun stuff
Launching Google Maps from your web app
Advanced
Change stylesheet, show/hide content on orientation change
Submitting your web app to Apple
Resources and links
Create a Twitter-like "Load More" widget
Resources for icons
Animated "loading" graphics
Tilable striped backgrounds
iPhone GUI PSD design template, version 4

INTRODUCTION

So you want to build your first web app for the iPhone, but you're just not sure how to get started. Here is a step-by-step guide to get you started. We are going to be using HTML (some HTML5), PHP, CSS, and Javascript in these lessons. Code samples are included.

DETECTING IPHONE TRAFFIC & REDIRECTION

First things first - who amongst your website's visitors are viewing your page on their iPhone, and how do you redirect them to your web app? We can do this with a simple PHP script placed at the top of your page before any header output. This will search the visitor's user agent string for the word "iPhone". If detected, they will be redirected to the URL you specify.
<?php

$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");

if ($iphone == true){

//Visitor is browsing on an iPhone, redirect them to your web app page
   header("Location: http://mywebapp.html"); 
    } else {
//Your visitor is not browsing on an iPhone
//Load your non iPhone optimized website here 
}

?>

SETTING UP YOUR BASIC PAGE FRAMEWORK

Scaling Your Page to Fit the Viewport Window

The iPhone viewport dimensions are 320x480 pixels. For your content to be readable without zooming your page needs to be scaled to fit the viewport width. To do this we are going to add the following meta tags between the <head></head> tags of the HTML.

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />

This will detect the visitor's device width and scale your page appropriately, whether in portrait or in landscape mode.

Adding also the following meta tags will enable your web application to run in "Full Screen Mode", which means that when launched from the home screen the address and status bars will vanish, making your web app appear just as a native iPhone app would.

<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

To launch a web app in full screen mode it must first be added to home screen. This is as easy as tapping the action icon in the status bar, as if to add as a bookmark, but instead tap the button "Add to Home Screen". An icon will be added to your home screen that can be launched just like a native iPhone app.

Note: the only drawback to this is that your web app will only stay in full screen mode until a link is clicked, which will launch your application in the Safari browser. If you have a single page application, though, full screen mode is ideal and goes a long way to enhance the viewer's experience. Additional data can also be loaded into your page without breaking full screen mode with the use of AJAX requests and a little ingenuity.

Defining An Icon For Your Web App

You can define a custom icon for your web app by including the following code between the <head></head> tags of your HTML.

<link rel="apple-touch-icon" href="icon.png" />

Your icon must be 57x57 pixels. By default, the iPhone will round the corners of your icon and overlay it with the famous glossy gradient, making it look like a three dimensional button. If the glossy overlay is not to your taste or washes out the graphic, you can opt to keep your icon "unglossed" by adding "precomposed" to the rel attribute.

<link rel="apple-touch-icon-precomposed" href="icon.png" />

Defining A Startup Splash Image

When launching your application from the Home Screen you can opt to display a startup splash image of your choice. Include the following code between the <head> tags of your HTML.

<link rel="apple-touch-startup-image" href="startup.png" />

The startup image must fit the dimensions of the viewport, minus the height of the status bar, which would be 320x460 pixels.

Note: "startup.png" can be changed to the actual path and filename of your image, but it must be in .PNG format.

Hiding the Address Bar

Space is limited, so it is critical to hide that pesky address bar from view. The following JavaScript snippet placed between the <head></head> tags of your page will cause it to "disappear" after your page has loaded.

<script type="application/x-javascript"> 
     
   addEventListener("load", function() 
   { 
   setTimeout(updateLayout, 0); 
   }, false); 
   
   var currentWidth = 0; 
   
   function updateLayout() 
   { 
   if (window.innerWidth != currentWidth) 
   { 
   currentWidth = window.innerWidth; 
   
   var orient = currentWidth == 320 ? "profile" : "landscape"; 
   document.body.setAttribute("orient", orient); 
   setTimeout(function() 
   { 
   window.scrollTo(0, 1); 
   }, 100); 
   } 
   } 
   
   setInterval(updateLayout, 100); 
   
   </script> 

Note: this simply pushes the address bar up above the page and out of sight, but it is still there. Scrolling up will cause it to come back into view.

Force Mimimum Screen Height With CSS

If your page doesn't have enough vertical content to fill the height of the screen the address bar will still hang in view. Also, if you have a footer it will drift up to where your content ends instead of sticking at the bottom of the page where it belongs. You can work around this by forcing the page height with some CSS. Add these styles to your CSS stylesheet.

html, body {
   height: 100%;
   margin: 0;
   }
#content {
   min-height: 100%;
   height: auto !important;
   height: 100%;
   margin: 0 auto -40px;
   }
#footer, #push {
   height: 40px;
   }

The "content" <div> will be the container element for all of your page content with the exception of the footer content. The negative margin (-40px, you can change this to whatever you want) must equal the same number of pixels as the "footer" and "push" height. This forces the page height to 100% and pushes your footer to the base of the page where it belongs.

The structure of your HTML is as follows.

<html>
  <head>
   </head>
    <body>
     <div id="content">
     <p>Your website content.</p>
     <div id="push"></div>
     </div>
     <div id="footer">
     <p>Footer text.</p>
    </div>
  </body>
</html>

Note: it is important that none of your page content falls outside the "content" and "footer" divs.

You now have your basic page framework in place. You can use this as a template and start adding content!

STYLING YOUR CONTENT

iPhone native and web apps have a certain branded and recognizable look. We are going to cover a few fundamental styles that emulate some of these looks. Because we are working with small screens your focus should be on enhancing readability with appropriately sized text and either a light color scheme or colors with good contrast. It is a good idea also to test your web app outdoors as brighter lighting conditions can make subtle patterns and colors difficult to distinguish. There are no rules, just use good judgement!

Something else to keep in mind is to avoid any fixed positioning with your elements, as the iPhone will ignore these and they will scroll along with the rest of the page.

* Optionally, you can take a look at the iWebKit framework that has many styles and images preconceived for quick and convenient implementation: http://snippetspace.com/projects/iwebkit/

Margin, Padding and Background

In the effort of keeping your web app quick loading it is ideal to use solid colors or small, tileable images for the background.

Tip: Stripe Generator 2.0 is an awesome resource for quickly generating striped background images on the fly. Check it out: http://www.stripegenerator.com/

Set your margin and padding both to 0, and define your background color or path to tileable image.

html, body {
   background: #ccc url(../images/background.jpg);
   margin: 0;
   padding: 0;
   height: 100%;
   }

Text Size

Text will automatically resize on orientation change despite the fact that you may have already defined text size. Sometimes this can really ruin the look of your web app. If you would like to disable this, add the following style to your html, body tags.

html, body {
   -webkit-text-size-adjust: none;
   }

Lists

You can customize the look of unordered lists to meet the display requirements of just about any type of content. We are going to round the edges using -webkit-border-radius, add a border to the bottom of each <li>, and remove the bullet from display.

ul {
   background-color: #e9e9e9;
   border: 1px solid #ccc;
   width: 95%;
   display: block;
   position: relative;
   padding: 0; 
   margin-left: auto;
   margin-right: auto;
   -webkit-border-radius: 12px;
   }
ul li {
   color: #333;
   font: bold 15px Geneva, Arial, Helvetica, sans-serif; 
   vertical-align: middle;
   border-bottom: 1px solid #ccc;
   list-style-type: none;
   text-align: left;
   white-space: nowrap;
   overflow: hidden;
   height: 30px;
   list-style-type: none; 
   display: block;
   padding: 15px 5px 5px 10px;
   }

The following code will make sure that child elements will have curved edges at the top and bottom of the list. -webkit-border-radius here should be the same as it is on the parent element.

li:first-child { 
   border-top: 0;
   -webkit-border-top-left-radius: 12px;
   -webkit-border-top-right-radius: 12px;
   }
li:last-child { 
   border-bottom: 0;
   -webkit-border-bottom-left-radius: 12px;
   -webkit-border-bottom-right-radius: 12px;
   }

If your lists are links, an arrow is a good way to quickly indicate that the feild is clickable. You can do this by setting the background property of the <li> with an image of a right facing arrow or chevron. I'm using a chevron that you can download here.

ul li {
   background-image: url(../images/chevron.png);
   background-position: right center;
   background-repeat: no-repeat;
   }

You should add right padding to compensate for the width of the chevron so that it is not overlapped by text.

ul li {
   padding-right: 15px;
   }

These are some basics to get you started with lists. You can experiment with different background colors, borders, padding, and font sizes. If you prefer lists that fill the entire width of the screen, simply change the <ul> width to 100%, set left and right margins to 0, and remove the -webkit-border-radius.

Creating An iPhone-Like Search Box

If you like the look of the iPhone's round-edged search boxes, here is some CSS to get you started. First, we create an <ul> with the class "form", make it 100% wide with no margin, and choose a background color.

ul.form {
   background-color: #999;
   width: 100%;
   margin: 0;
   }

For the <ul> background color to show we set the <li> background to "none" and align everything to the center.

ul.form li {
   background: none;
   text-align: center;
   }

Now we create a class named "searchbox" for the input field. What will make this look like a native iPhone search box is the rounded edges. For a height of 25px I've selected a border radius of 12px; This creates a deep, round curve.

ul.form li input[type="text"].searchbox {
   color: #333;
   background: #e9e9e9;
   border: 1px solid #ccc; 
   font: normal 15px Arial;
   width: 80%;
   height: 25px;
   padding: 0 0 0 8px;
   display: inline-block;
   margin: 0 10px 0 0;
   -webkit-border-radius: 12px;
   }

Here you can define the path to a background image for the "submit" button. I'm using a magnifying glass image that you can download here.

ul.form li input[type="submit"].search {
   background-image: url(../images/search.png);
   background-position: right;
   background-repeat: no-repeat;
   width: 24px;
   height: 24px;
   border: 0;
   padding: 0;
   margin: 0 10px 0 0;
   display: inline;
   vertical-align: middle;
   }

The HTML for your search box should look like the following:

<form method="post" action="yourscript.html">

<ul class="form">

<li><input name="searchfield" type="text" class="searchbox" placeholder="Search Content" /> <input type="submit" name="Submit" class="search" /;></li>

</ul>

</form>

Form Field Placeholder

You may have noticed the "placeholder" input field attribute. This is one of the groovy features of HTML5 which allows you to display text in the input field that will clear when the field is clicked on. This is awesome because you no longer need to use JavaScript to do this.

<input name="myfield" placeholder="Your Placeholder Text" />

Form Field Autofocus

To set the focus on a specified field when the page loads, use the form field attribute "autofocus".

<input name="myfield" autofocus />

Form Field Autocomplete

Depending on your application, the iPhone form field feature "autocomplete" can be a nuisance. You can turn this off, however, as shown in the following example.

<input name="myfield" autocomplete="off" />

Form Field Autocapitalize

The same can be done for autocapitalization in a form field. This is important if your form input is case sensitive.

<input name="myfield" autocapitalize="off" />

Form Field Types

Since different types of input fields sometimes require a different set of characters, Apple has implemented some great input type features that will display a different keyboard for each. For example, a form field with an "email" type would display a set of characters that you need for typing email addresses - including the "at" sign, and "dot".

Here are some different types that you can specify.

URL

 <input type="url" name="myfield" />

Email

 <input type="email" name="myfield" />

Number

 <input type="number" name="myfield" />

FUN STUFF

Launching Google Maps From Your Web App

The iPhone will actually do this for you automatically if you link to a Google Map URL. For example, you want to link to the map for the Museum of Modern Art in New York City. The address is:

11 West 53rd St
New York, NY 10019

The URL format for that would be:

<a href="http://maps.google.com?q=11 west 53rd st new york ny 10019">

Spaces in the URL are ok. When the link is clicked, the Google Maps app will launch. It's as easy as that.

ADVANCED

Change Stylesheet, Show/Hide Content on Orientation Change

Sometimes you may wish to have seperate CSS styles for portrait and landscape mode. If that is the case, you can easily switch between the two with a bit of JavaScript. Place the following code between the <head></head> tags in your HTML.

<script type="application/x-javascript">

	window.addEventListener('load', setOrientation, false); 
    window.addEventListener('orientationchange', setOrientation, false);
    function setOrientation() { 
    var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait'; 
    var cl = document.body.className; 
    cl = cl.replace(/portrait|landscape/, orient); 
    document.body.className = cl; 
    }

 </script> 

Add the class name "portrait" to your <body> tag.

<body class="portrait">

Lastly, customize your CSS stylesheet.

body.portrait { 
   background-color: black; //page background will be black
   }
body.landscape { 
   background-color: white; //page background will be white
   }

Idea Storm

Here is a great idea - if you have a <div> in your page with the ID "hidden", the content within that <div> will appear only when the phone is in landscape mode (or vice versa, depending on how you customize the CSS). This is an invaluable way of displaying content that requires varying widths. For example, portrait mode could display chart data for the previous 7 days; landscape mode could display chart data for the previous 30 days. Or you could modify this to display a thumbnail image in portrait mode and a full sized image in landspace mode. The possibilities are endless.

body.portrait #hidden { 
   visibility: hidden;
   height: 0;
   width: 0;
   padding: 0;
   margin: 0;
   display: none;
   } 
   
   body.landscape #hidden { 
   visibility: visible;
   display: block;
   }

SUBMITTING YOUR WEB APP TO APPLE

So you've got a great web app that a lot of people will find useful, and you want to submit it for inclusion in Apple's web app gallery (http://www.apple.com/webapps/). To do this you will need to register for a developer account. This is free, you just need to choose an ID, password, and give a few details about yourself or company and the type of products you develop.

You will need an application screenshot and a product icon to submit your web app to Apple. The screenshot is as simple as taking a snapshot of your app from your iPhone by pressing the "Home" button and the "Sleep" button together. The screen will flash and the screenshot will be saved to your Camera Roll.

The dimensions of your application screenshot must be 320x436. Open your screenshot in an image editor program and crop off the Safari toolbar at the bottom, which is 44 pixels high. This will make your screenshot the exact size it needs to be. This can be saved as a PNG, GIF, TIFF, or JPEG, and the file size must be less than 1MB.

Apple requires that your product icon be 128x128 pixels, include alpha transparency and be in PNG or TIFF format. I like to make my icons with rounded edges as they would appear on the iPhone. You can do this in Photoshop by drawing your icon base using a rounded rectangle tool over an empty layer. When you've finished your design, select "Save for Web & Devices" in .PNG format.

It can take a couple of days to several weeks for your web app to be reviewed by Apple. Good luck with your submission!

RESOURCES AND LINKS

Create a Twitter-Like "Load More" Widget
http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/

Resources For Icons
In my opinion one of the best free icon sets for your iPhone application or web app are from Glyphish.com. You can also purchase double sized versions for optimal, crisp rendering on the high resolution iPhone 4 display.
http://glyphish.com/

Animated Loading Graphics
Customize your own "loading" graphic.
http://ajaxload.info/

Tileable Striped Backgrounds
Generate striped background images on the fly. Check it out:
http://www.stripegenerator.com/

iPhone GUI PSD Design Template, version 4
http://www.teehanlax.com/blog/2010/06/14/iphone-gui-psd-v4/

Ting-Tong | Cowboy Action Town | Tutorials | About Me | Contact

Copyright © Jamie Butler