Six Revisions Menu
Main Categories
CSS HTML JavaScript
Web Design WordPress Web Development
Design Inspiration UX Design UI Design
Freebies Tutorials Tools
Links
About Contact Advertise
RSS Twitter Facebook

How to Make an HTML5 iPhone App

By Alex Kessinger

Advertisement

spacer

You’ve been depressed for like a year now, I know. All the hardcore Objective-C developers have been having a hay-day writing apps for the iPhone. You might have even tried reading a tutorial or two about developing for the iPhone, but its C—or a form of it—and it’s really hard to learn.

I don’t want to say that you should give up on the objective: you can get it eventually. But in the meantime, there is something else that you can do.

You can create a native app that lives with all the other apps, and for the most part, it’s going to be a pitch-perfect imitation.

You can do this with the skill set you probably already have: HTML(5), CSS, and JavaScript.

I’ll show you how to create an offline HTML5 iPhone application. More specifically, I’ll walk you through the process of building a Tetris game.

Offline?

What am I talking about when I say "offline"? Well, it means that we have a custom icon, a custom startup screen, a native look-and-feel, and you can use the app even when the phone isn’t connected to the Internet.

The app should be as functional as it can when it is offline, just like normal native mobile apps.

This is a tutorial specifically for iPhones but most of these techniques apply to all phones that have HTML5-capable browsers.

Yeah, I mean it, check out the following image. It has no URL bar and no navigation at the bottom. It looks just like a native mobile application.

spacer

Prework

You are going to need access to a server where you can change the HTTP Headers on your files. This is because we need to take advantage of HTML5’s offline caching (more on this later down the page).

Apache does this really well and you can just add something to a .htaccess file and it will just work. Here’s a tutorial on modifying HTTP headers using htaccess.

The other thing you need to do is to enable the debug bar in Safari’s web browser on your iPhone unit. Go to the Settings.app > Safari > Developer on your iPhone, then turn on the debug console. This will help you spot potential JavaScript errors.

Once you’ve built your app, you should turn this off so that you will get the full experience when testing your HTML5 iPhone app.

spacer

About the App

Icon and Startup Screen

The icon needs to be 57px x 57px.

The iPhone will round the corners of your icon, create a dropshadow, and add a shine to whatever icon you use.

It should be in PNG or JPG format.

Here is what I used for the tetris game.

spacer

The startup screen needs to be 320px x 460px and should also be in PNG or JPG format.

Here is what I used for the startup screen.

spacer

Some tips before you start

Stay small, sparse and simple.

Application Cache

This is a new standard, you can read the spec here.

Application caching allows browsers to determine in advance all the files a web page will need for the web page to work.

It will cache those files (to a fault, sometimes). The syntax of this file is simple: just list the locations of your files in either absolute (e.g. yourwebserver.com/picture.png) or relative to the manifest file (/picture.png). The browser will keep those files offline.

You can also list a few URLs that should not be cached, but this isn’t pertinent for our offline app (if you’re interested, read about this in the documentation).

One tricky part to this whole thing is that the manifest (the list of files that need to be cached offline) has to be passed with a filetype Header set to text/manifest. That is why you need access to a web server that can set HTTP headers.

Screen Size

A quick note when designing your application: When you are in app mode, you have a screen size of 320px x 460px. When you are in web mode, it has a screen size of 320px x 356px. This can affect the user interface of your offline HTML5 app.

Here you can see the difference side by side.

spacer

HTML

It’s a real browser so your HTML is exactly the same. The iPhone browser is also in the forefront of HTML5, so dig into the spec.

For more in-depth detail, check out the Safari Developer’s corner:

Let’s get coding

The app starts by defining your markup. here is the markup for my Tetris app.

<!DOCTYPE html>
<html manifest="tetris.manifest">
<head>

    <meta name="viewport" content="user-scalable=no, device-width, initial-scale=1.0, maximum-scale=1.0"/>
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <link rel="apple-touch-icon" class="iphon_tetris_icon.png"/>

    <link rel="apple-touch-startup-image" class="startup.png" />
    <link rel="stylesheet" class="tetris.css" type="text/css" media="screen, mobile" title="main" charset="utf-8">

    <title>offline Tetris</title>
</head>
<body>
   <!-- Put your Markup Here -->
   <script type="text/javascript" src="/img/spacer.gif"> 

First, notice the Doctype. Isn’t HTML5 awesome?

The manifest="cache.manifest" property on the <html> tag is how the browser knows that we want to cache this web page offline.

There’s proprietary Apple markup on our HTML5 page. A brief explanation of each:

  • apple-mobile-web-app-capable: This is another tip-off that we want to be an offline app.
  • apple-mobile-web-app-status-bar-style: This hides the status bar, and nav bar when the app is offline.
  • apple-touch-icon:This is the pointer to the image that want to be the icon.
  • apple-touch-startup-image: This is a url pointing to the startup image.

Also note that you should put CSS at the top and JavaScript at the bottom (best practices still apply here).

CSS

It’s almost the same as a normal web page. There are some specific -webkit CSS rules that you can use that do some really cool things like animation, but this is a quick-and-dirty guide and that’s outside of the scope of this article.

The CSS is just Plain Jane.

body {
    overflow:hidden; 
    background: #d7d7d7;
    margin:0;
    padding:0;
}
#tetris {
    px;
    px;
    background:#000;
}

The style is really just to the div element on our web page to make sure it fits in the iPhone’s viewport properly.

JavaScript

I used a modded version of a JavaScript from Dalton Ridenhour; I found it on Github. The JS was written originally for a normal web browser. The only modifications I had to make was to support not having a keyboard.

In general, JS functions work just fine on the iPhone—there are exceptions though. Think about something like a mouseover, the event exists on the iPhone, but I am not sure how helpful it is when you don’t have a standard pointing device (such as a mouse). Quirksmode posted an article about events on the iPhone that is really helpful.

When you have all of that, you can test it out but opening your index.html in an iPhone, and you should be able to see everything work.

Then, next step is to server it from an actual webserver that can set the proper settings on the cache.manifest.

Then you could be able to add it to the home screen and have all the extras, and see the offline mode.

You can see a working version I have set up at:

  • tetris.alexkessinger.net

Bonus Section: Offline Data

Along with the ability to keep files that are needed offline, you can also store user data in an offline database. There are two major APIs for per user and/or per page data. The first is localStorage. localStorage, is an easy to use key-value store with a dead simple API.

localStorage.dataToStore = 5;
console.log(localStorage.dataToStore); // 5 

You can use this for storing the user’s score, for example.

The second is actually an offline SQL engine, a webdatabase. The APIs are a little more advanced. Here is a little of you will see.

// Try and get a database object
var db;

try {
    if (window.openDatabase) {
        db = openDatabase("NoteTest", "1.0", "HTML5 Database API example", 200000);
        if (!db)
            alert("Failed to open the database on disk.  This is probably because the version was /
            bad or there is not enough space left in this domain's quota");
    } else
        alert("Couldn't open the database.  Please try with a WebKit nightly with this feature enabled");
} catch(err) { }

// Check and see if you need to initalize the DB
db.transaction(function(tx) {
    tx.executeSql("SELECT COUNT(*) FROM WebkitStickyNotes", [], function(result) {
        loadNotes();
    }, function(tx, error) {
        tx.executeSql("CREATE TABLE WebKitStickyNotes (id REAL UNIQUE, note TEXT, timestamp /
        REAL, left TEXT, top TEXT, zindex REAL)", [], function(result) { 
            loadNotes(); 
        });
    });
});

// Insert a test Note. 
var note = {
    id: "1",
    text:" This is a test note",
    timestamp: "112123000",
    left:10,
    top:10,
    zIndex:2
};
db.transaction(function (tx) 
{
    tx.executeSql("INSERT INTO WebKitStickyNotes (id, note, timestamp, left, top, zindex) VALUES /
    (?, ?, ?, ?, ?, ?)", [note.id, note.text, note.timestamp, note.left, note.top, note.zIndex]);
}); 

// Get all the notes out of the database.
db.transaction(function(tx) {
    tx.executeSql("SELECT id, note, timestamp, left, top, zindex /
    FROM WebKitStickyNotes", [], function(tx, result) {
        for (var i = 0; i < result.rows.length; ++i) {
            var row = result.rows.item(i);
            var note = new Note();
            note.id = row['id'];
            note.text = row['note'];
            note.timestamp = row['timestamp'];
            note.left = row['left'];
            note.top = row['top'];
            note.zIndex = row['zindex'];

            if (row['id'] > highestId)
                highestId = row['id'];
            if (row['zindex'] > highestZ)
                highestZ = row['zindex'];
        }

        if (!result.rows.length)
            newNote();
    }, function(tx, error) {
        alert('Failed to retrieve notes from database - ' + error.message);
        return;
    });
});

Wrap Up

There is lot that can be done with offline HTML apps. Games, like tetris, are even possible, but you would probably want to consider what you want to do and make sure its right for an offline app. Quake 3 Arena, probably not. A to-do list app, definitely.

Let thousands apps bloom!

Resources

  • W3C Offline Application Cache docs
  • How to create offline webapps on the iPhone
  • The HTML5 offline cache safari
  • Backchannel: an Offline-Capable Web App for the iPhone
  • iPhone offline webapps – a desk on iPhone apps.
  • A disscussion of offline events by John Resig
  • Getting Started with iPhone Web Apps

Related Content

  • 10 Useful Gadgets for Mobile Computing
  • A Quick Look at Mobile Web Designs
  • The Remote Designer: How to Work While on the Road
  • Related categories: Web Development and User Interface

About the Author

spacer Alex Kessinger works for Yahoo! as a front-end engineer. Elsewhere, he likes to curate great stuff from the web on his blog, alexkessinger.net. He is also a founding member of the Tastestalkr Network, a brand group. When not working, Alex lives in the bay area and enjoys really good food.

This was published on Mar 26, 2010

Previous PostNext Post

172 Comments

Sachin Mar 26 2010

I simply love this……Yahoooooooooooooooo!

Matthew Heidenreich Mar 26 2010

very creative article, nice job Alex.

Ben Mc Mar 26 2010

Excellent article! This mostly works for the Android as well.

TimHolmesDesign Mar 26 2010

I had no idea you could develop an app for the IPhone using HTML5… soooooo cool and opens it up to so many more who don’t have the C skills.

Cheers for the great post.

Tim

insic Mar 26 2010

Superb tutorial. Thanks for sharing.

tom Mar 26 2010

Nice and simple tutorial, will be using this information very shortly

Haeussler3968 Mar 26 2010

Very cool, I really enjoyed it. Do you know of somewhere I can read more about it?

dolce Mar 26 2010

awesome – very interesting article

A. Cobo Mar 26 2010

Genious use of new and upcoming web standards

Graphpix Mar 26 2010

Thanks ;)

Ched Mar 26 2010

Is it possible to submit your app to the Apple AppStore? Or is it just a web app?

Guhan Iyer Mar 26 2010

Very intriguing article. I would caution folks using this technique to keep the Javascript light weight due to the memory restrictions on the iPhone. Thanks for posting!

BBL Mar 26 2010

great !!!!

Alex Kessinger Mar 26 2010

No, you can’t submit these kind of apps to the app store. Though you can look up this thing called phonegap, and run these kinds of apps inside and iPhone app, and then submit them to the app store.

naefaaxx Mar 26 2010

?????????????????????

Askar Sabiq Mar 26 2010

whoa, very nice tuts !

selvagk Mar 27 2010

Excellent..

Another Dave Mar 27 2010

Great tutorial, thank you!

Although you should remove any references to the name of the game, which might be trade marked.

Mahmudur Rahman Mar 27 2010

Very understandable and well explained tutorial. Thanks for sharing this nice post. :)

Eric Perduel Mar 27 2010

Some people just don’t learn. Go ahead, repeat all the mistakes done with IE, browser sniffing, etc.

Next articles:
How to Make an HTML5 Symbian App.
How to Make an HTML5 MeeGo App.
How to Make an HTML5 Android App.
How to Make an HTML5 WebOS App.
How to Make an HTML5 Blackberry App.
How to Make an HTML5 WinMo App.

How about following the W3C specs (widgets, HTML5, CSS3)?And stop using proprietary sh*t which is EXACTLY as idiotic as doing something with ActiveX or for IE specifically?

Bruno Daniel Mar 27 2010

Great post, thank you. A quick tip: in your demo, the user can swipe and the whole screen will move, but this is easilly fixed by adding this meta tag:

Bruno Daniel Mar 27 2010

Hmm, seems the comment won’t accept HTML. Here’s the tag with brackets:

[meta name=”viewport” content=”device-width, user-scalable=no” /]

Hans Mar 27 2010

Very cool artikle and no restriction from Apple. thx for the work.

adkarta Mar 28 2010

wow,,,never thing that this is possible.

Bartosz Oczujda Mar 28 2010

One important question. Can you do it on a PC? And submit it to the app store?

Doug Montgomery (Douglife) Mar 28 2010

Alex, I’ve been doing some research on creating apps, and even to a coder some of the stuff is intense. Cocoa, ObjectiveC, etc. I wasn’t looking to create a whole game, just some great features for clients with Iphones. This has done it for me my friend, and I thank you.

Great tutorial by the way, well detailed, and to the point!

zpjet Mar 29 2010

@Bartosz: yes you can. Download and install Safari, go to Preferences > Advanced, turn on Develop menu, then you can change user agent to iPhone. You also don’t need iPhone to test it – iPod Touch is the same Mobile Safari device.

Alessio Bellisomi Mar 29 2010

Cool, but Perduel’s suggestions should be seriously considered

Aleksander Aas Mar 29 2010

Make sure to lay of the -webkit- nonsense and HTML5 apps are the future!

Jasper Mar 29 2010

You can also use www.appcelerator.com/ to convert it into a real app, with native capabilities.

Nikos Mar 29 2010

Nice Article. Thanks for sharing!

jacopogio Mar 29 2010

as usaul, Alex, a very very good and interesting post !

Waiting for my android HTC tu upgrade to 2.1 to try something similar ;-)

Brady J. Frey Mar 29 2010

Thanks for this, there were a couple here I’d yet to hear of!

On an odd note, I know you may have copied and paste the code, but some of your tags are xhtml although you’re calling an html5 doctype. Now, it won’t necessarily mark you wrong, but it may warn you in a validator as bad habits and unneeded (see some of your meta and links).

…and in html5, script doesn’t require a type, as all scripts are javascript. Many thanks!

Vector king Mar 30 2010

I was abit scared at the beginning with all the http stuff but I managed to pull trough . Thanks Alex

stphen Mar 30 2010

well very nice techniques you have explained in order to develop HTML iphone app, very nice post with very exclusive content. thanks for this awesome post.

jaw crusher Mar 31 2010

It is good.

kv Apr 02 2010

@Alex

Not Q3Arena, and not demonstrated on a mobile device but someone’s getting close..
Original Quake in HTML5
ajaxian.com/archives/gwt-quake

Ashwin Apr 03 2010

Very nice article. Awesome intro to all HTML5 iPhone newbies like me. Thanks for sharing :)

Steve Judd Apr 03 2010

Thanks for this. I used your tutorial to guide me in building an “app” to help pick door prize winners (or other random numbers) for our users’ group meetings. Works in any compliant browser, and works offline on my Droid and iPod touch.

Andy matthews Apr 03 2010

I thunk you should be a little more clear about the fact that is NOT an IPhone app, but an hmtl5 web app that’s cacheable on the iPhone.

wolf Apr 05 2010

Hi Andy,
wonder if jquery transition effects for images would be a problem. I assume not, since this would practically be a web app – right?!

Theron Burger Apr 05 2010

Awsome! Am def going to give this a try!
Another MAJOR plus is not having to go through the app store. You can make your app do whatever you want and apple cant do a dam thing about it.

@Eric Perduel
I am new to this and want to learn, I would prefer to learn the standards and make it cross platform. SO… why not tell us what is wrong with his code (according to you) so that we can lean. That’s what this is all about, learning, in a fun, collaborative way.

LabsMs Apr 06 2010

Thx for post.
I want to learn Html5 for use iphone and ipad

Giacomo Ritucci Apr 08 2010

I can’t find anything on Google about the “filetype” header. May it be “Content-Type”?

Also, I can’t find the “text/manifest” MIME Tipe, but I found the “text/cache-manifest” content type that seems the one we are looking for.

Can someone confirm?

Giacomo Ritucci Apr 08 2010

I managed to set the “text/cache-manifest” MIME type with the following .htaccess directive

AddType text/cache-manifest .manifest

It seems that mod_headers cannot set the Content-Type header.

BK Apr 18 2010

Nice tutorial. I was Googling on how to create app for Apple iPhone. I couldn’t agree more with you that “C—or a form of it—and it’s really hard to learn.” It is really not easy especially for someone with no programming background.

Chad Smith Apr 19 2010

Great post! Thanks for making the effort to put a number of disparate HTML5 references into a concise post with a cool code example.

Roy Smith Apr 28 2010

It’s worth noting that there are a number of development tool companies now offering cross platform development (iPhone, iPad, Android) based on HTML5,CSS,JS. appMobi(from FlyCast) and AppCelerator both do this.

Kaithy Aravind Reddy Apr 30 2010

Very good technical article for a device on a new concept. please post complete code for above thanks.

Jonathan Stark May 15 2010

Nice work! You might want to add -webkit-user-select: none; to the controls. Cheers!

Lang Zi May 17 2010

Very interesting article. You created an icon and startup screen for the app but they’re never been used in this article. My question is if it’s possible to create an icon in your iphone screen to make it just like a normal application.When you click the icon your application will be launched.

Lang Zi May 17 2010

Please ignore my questions. I found the answer by

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.