How to Make an HTML5 iPhone App

March 26th, 2010 by Alex Kessinger | 68 Comments | Stumble It! Delicious

Become a Facebook Fan of Six Revisions.

How to Make an HTML5 iPhone App

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.

Final result

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.

Prework

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.

Icon and Startup Screen

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.

Icon and Startup Screen

Some tips before you start

Stay small, sparse and simple.

  • Small: This is mobile app development so even though you are caching your stuff, it’s still a smart idea to keep your file sizes lean.
  • Sparse: You should try to keep the amount of files you deal with as low as possible.
  • Simple: Start with a few simple ideas and execute it. By keeping your scope small, you can get things done faster.

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. http://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.

Screen Size

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, width=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" href="iphon_tetris_icon.png"/>

    <link rel="apple-touch-startup-image" href="startup.png" />
    <link rel="stylesheet" href="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="tetris.js"></script>

</body>
</html>

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 {
    width: 320px;
    height: 460px;
    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:

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

Related Content

About the Author

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.

68 Comments

Sachin

March 26th, 2010

I simply love this……Yahoooooooooooooooo!

Matthew Heidenreich

March 26th, 2010

very creative article, nice job Alex.

Ben Mc

March 26th, 2010

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

TimHolmesDesign

March 26th, 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

March 26th, 2010

Superb tutorial. Thanks for sharing.

tom

March 26th, 2010

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

Haeussler3968

March 26th, 2010

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

dolce

March 26th, 2010

awesome – very interesting article

A. Cobo

March 26th, 2010

Genious use of new and upcoming web standards

Graphpix

March 26th, 2010

Thanks ;)

Ched

March 26th, 2010

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

Guhan Iyer

March 26th, 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

March 26th, 2010

great !!!!

Alex Kessinger

March 26th, 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

March 26th, 2010

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

Askar Sabiq

March 26th, 2010

whoa, very nice tuts !

selvagk

March 27th, 2010

Excellent..

Another Dave

March 27th, 2010

Great tutorial, thank you!

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

Mahmudur Rahman

March 27th, 2010

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

Eric Perduel

March 27th, 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

March 27th, 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

March 27th, 2010

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

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

Hans

March 27th, 2010

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

adkarta

March 28th, 2010

wow,,,never thing that this is possible.

Bartosz Oczujda

March 28th, 2010

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

Doug Montgomery (Douglife)

March 28th, 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

March 29th, 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

March 29th, 2010

Cool, but Perduel’s suggestions should be seriously considered

Aleksander Aas

March 29th, 2010

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

Jasper

March 29th, 2010

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

Nikos

March 29th, 2010

Nice Article. Thanks for sharing!

jacopogio

March 29th, 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

March 29th, 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

March 30th, 2010

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

stphen

March 30th, 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

March 31st, 2010

It is good.

kv

April 2nd, 2010

@Alex

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

Ashwin

April 3rd, 2010

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

Steve Judd

April 3rd, 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

April 3rd, 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

April 5th, 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

April 5th, 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

April 6th, 2010

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

Giacomo Ritucci

April 8th, 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

April 8th, 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

April 18th, 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

April 19th, 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

April 28th, 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

April 30th, 2010

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

Jonathan Stark

May 15th, 2010

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

Lang Zi

May 17th, 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 17th, 2010

Please ignore my questions. I found the answer by myself. But I got another question. Is it possible to add the icon to home screen by program. For example, the user access your web site and find your application. You add a link like “installing the application” which will add your icon to iphone’s home screen. The next time users will be able to click this icon to launch your app offline.

Richard

June 3rd, 2010

Is there a way to hide the status bar completely?

sreedhar.R

June 8th, 2010

Nice article

Jean-Philippe

June 9th, 2010

Thanks Alex. Nice article.
By the way, do you know any HTML5/Webapp-capable repositories where we can publish and get some snipets ?

I wrote a basic iPad layout, which adapts itself depending on device orientation. Anyone to help me getting it improved ?

I’d be pleased to share.

Bitelchux

June 14th, 2010

My first html5 game, compatible with iphone, ipad, android and desktop pcs
http://androidiphonewebapps.com/westernduel/html5.html

Laurie Cope

June 18th, 2010

This is great. Just about to start iphone app development this will come in handy for web apps. thanks

Joshua

July 1st, 2010

Great article. What have you found to be the practical limit to the ammount of data that can be cached on the iPhone?

Fuzebit

July 2nd, 2010

Excellent article. Working example is great.

hitesh vaghela

July 9th, 2010

Hi!!!!!!!
It’s very fine article for basic fundamental Knowlenge

Xeno

July 17th, 2010

Does not work for me using the iPhone G3S with software version 3.1.3 and Safari

Perhaps an update by apple stopped this bit of fun?

On my own server, using your example site, and also over at whatreallyhappened.com, I can only view in Safari as a web page, but not as an app.

Anyone get this to work recently?

Mike

July 17th, 2010

How about showing us one with flash code? Considering the latest EU actions against apple, it looks like they’ll be forced to accept them on the iApps store soon enough.

Brady J. Frey

July 18th, 2010

No one cares about Flash, Mike, even with the court debate. Besides, as bloated, proprietary code, you will be forced to use their paid flash application to build and render it. Buy flash and experiment, no need for a tutorial- that’s the same as me teaching you cobalt, it’s vintage quaint.

Brett

July 21st, 2010

Great article but I believe you are overlooking a much better reason to use HTML5 over Objective C to develop. That reason is it offers the only way for your work to be cross platform. What do I mean by this, if you write in HTML5 generically then it can run in Iphone, IPad, Droid and whatever else is thrown our way coming up. Even Blackberry is moving to WebKit which will support it. This opens up a whole lot more market to one written in something that is already cross platform. If you write a big bloated application in Objective C and discover you could make more money having an Android version too then voila you now have to rewrite the whole thing from scratch. However, this isn’t the case writing it with HTML5. That is why it is key to use especially in the long run. Now if building an app good idea to have a backend code in any other language you want, Java, C#, etc and use REST services or jsps or whatever.
Also, Steve Jobs said it would be over his dead body before he will allow Flash to run in IPhone which pretty much puts Adobe’s product into crapville.

MO

August 3rd, 2010

Great post! Thank you so much Alex
Quick questions, if the website that your working off is a CMS site running with Joomla how do you know what files to include in the manifest? Does this even work with CMS. Basically to make the site look like an app and to be able to flick through the pages of the site while still in the app screen?

flashmac

August 12th, 2010

Ironic, I’ve just jumped from your HTML5 tut on nettuts (was googling your’ viewport’ tag) and landed here! Man your everywhere!!

Mr personal HTML5 hero today!

Joe

August 13th, 2010

Look at this:

http://nocore.info/games/minesweeper/

optimized for iPhone/PC, also runs with HTC Desire

Michael Persson

August 16th, 2010

I have study the HTML5 from 2008 and had some interesting experiences, this is a little new and of course interesting to start trying. HTML5 is a FLASH KILLER and only that is very interesting for practice…

Leave a Comment

Subscribe to the comments on this article.