O'Reilly logo

Learning the iOS 4 SDK for JavaScript Programmers by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Why Go Native?

Those who frequently develop mobile web applications with HTML, CSS, JavaScript, and related technologies tend to find a way to reuse those comfortable tools for every app challenge. The iOS (formerly iPhone OS) platform has attracted much attention in the web developer community, and Apple continues to evangelize web app development for the platform.

At the same time, there’s evidence of a desire among developers to adapt their web technologies to replicate the look and feel of native iPhone and iPad apps, whose look and feel users know from the built-in apps and other apps downloaded from the App Store. Perhaps you’ve used third-party libraries, such as iUi or jQTouch, to deploy your content and application ideas so that they look and behave like native iOS apps.

Despite advances in web technologies—especially the HTML5 and WebKit extensions to CSS and Document Object Model (DOM)—an iPhone or iPad web app lacks access to several key facilities built into iOS. You must also deal with the Mobile Safari browser address bar, especially if your users aren’t experienced enough to generate a home screen icon for your app. Additionally, even though both your iPhone-specific styles and scripts target a single OS platform, you still may encounter compatibility issues with earlier versions of Mobile Safari running on iPhone and iPod touch units in the field that haven’t been updated to the latest OS versions. For example, I saw from my server logs that nine months after the release of iPhone OS 3.0, some users of my native iPhone apps continued to use iPhone OS 2.2, especially with iPod touch devices (most of whose users once had to pay for major OS upgrades).

In other words, the choice to reach iPhone and iPad users through web applications, which were supposed to simplify development, introduces its own set of complications. Maybe it’s time to make the leap and start developing native iOS apps. This chapter highlights iOS features you can use if you choose to develop native apps—features that are not available to web-only apps. Even if your app designs don’t require a lot of native OS support, a native app still has advantages over web apps. To provide a fair and balanced picture, I’ll also discuss what you lose by using a native app over a web app.

Using an App Offline

It is hard to argue with the fact that iOS devices are intended to be used in a connected world. WiFi is built into all devices by default; iPhones and iPads (and likely future devices) equipped with 3G also have cellular data connections that free users from lurking around WiFi hotspots. Unfortunately, users may be out of WiFi range, have no cellular connection, be running dangerously low on battery power, or be secured inside a jet-powered flying metal tube whose attendants prohibit radio contact with the ground. When an iOS device cannot access the Internet, a traditional web app—which resides entirely on your web server—is not accessible. Although it is possible to code a browser-based web app to be copied and stored on a device, the mechanism isn’t foolproof.

A native app, however, is at least launchable even when the device has no connection to the Internet. Exactly how usable the app is while offline depends on the nature of the app, of course, but it’s clear from the apps that Apple supplies on every device that an iOS device does not completely die if Internet connectivity is missing. You can still listen to music, watch previously downloaded videos, look up your contacts, and tap out notes; with an iPhone and iPod touch, you can still be awoken by an alarm or calculate a total; and with any camera-equipped device, you can take pictures. Applications you download from the App Store let you do tons more things, such as play games, read gorgeous-looking downloaded books, edit photos, figure out restaurant bill tips, look up a dictionary definition, or identify a bird in the nearest tree—all without the need for a constant Internet connection.

Many native apps also connect with the Internet for some functions. Games commonly upload scores so you can see how well you perform against other users around the world. Many apps also rely on the Internet for up-to-date information, such as email apps, news readers, weather apps, Twitter and Facebook clients, and many more. For designers of many of these types of apps, the challenge is to create an app that can perform its basic functions offline, even if it means the user needs to download some current content before cutting the wireless cord. Once disconnected from the cloud (perhaps even while flying above the clouds), the user can relaunch the app and still access fairly recent content.

Unfortunately, you cannot rely on Mobile Safari to preserve a downloaded web page’s content for long. Even if the user manages to keep the Safari window open, restoring it for use sometimes causes the page to attempt to reload itself from the server. No server? No content, even though it may be in a cache someplace on the device.

Some web apps have successfully been converted to bookmarklets. A bookmarklet is a browser bookmark that contains a javascript: or data: URL whose code generates the HTML, CSS, image data, and JavaScript code for a web page when chosen from the browser’s bookmarks list. It’s true that this method allows a web app to be stored entirely on the user’s device, but a web page generated in this fashion has some additional limitations over regular web pages. For example, a bookmarklet app cannot use browser cookies because of security restrictions in the browser.

Mobile Safari does support the HTML5 offline application cache. This mechanism allows web app publishers to code their pages (and configure their web servers) in a way that allows the browser to store a copy of a web page and additional resources (e.g., images) on the device. Developers deploying this technique have a variety of limits to attend to, such as a maximum of 25 KB for any resource file, including any images. Of greater concern, however, is that if the user reboots the device (completely powering down the unit), all data in this offline cache can be lost. Native apps, however, survive such system reboots every time.

There is a risk that when you have been designing Internet-based content and software for a long time, you tend to take Internet connectivity for granted—after all, you have always-on broadband at home or work. Additionally, all the buzz about cloud computing makes it sound as though every computer user on the planet has ubiquitous and nearly free access to an Internet that is as reliable as the sun rising tomorrow morning. That is not always the case for all users.

More Access to the Hardware

It doesn’t take long to learn that web pages developed for general-purpose web browsers are encumbered with many restrictions. For example, a web page does not have free rein over the host computer’s filesystem, making it impossible for well-meaning scripts to read or write files on the hard disk (except for closely monitored dedicated files for items such as cookies and HTML5 data storage). JavaScript is granted very limited access to even the host browser’s environment or settings. Despite the possible convenience afforded by automatically adding the current web page to a user’s bookmarks list, such access is out of bounds for web pages.

All of these restrictions, of course, are imposed for the sake of security and privacy. Left unfettered, a script on a malicious hacker’s website could wreak havoc on every browser that lands at the site. Not many users would like unknown computers reading their recent browser histories or replacing system files with ones that could cause banking website visits to be redirected to lookalike phony sites that capture usernames and passwords. Cyber crooks are constantly on the prowl for vulnerabilities in popular browsers that they can exploit without the user’s knowledge—the so-called drive-by attacks that have plagued various browsers through the years.

An application designed to run natively on popular desktop computer operating systems, on the other hand, typically has exceptionally broad freedom to rummage around the computer at will. On some operating systems that are set up for user accounts, the user must grant specific permission to the program’s installer. Such permission is taken to mean that the user trusts the installer and the program(s) it installs to do no harm. Developers who publish software with a goal of building a software business avoid doing bad things to customers’ computers even though users essentially hand over the key to the system. On the other hand, if a program has a hidden agenda (e.g., loading spyware onto every user’s computer), the nefarious activity will likely be discovered sooner or later. News of the offenses will carry quickly across the Internet and the company’s reputation will be ruined.

Apple engineers have thus far greatly restricted the hardware features available to web apps running in Mobile Safari. Despite some cool hardware, such as the digital compass in the iPhone 3GS, web apps simply have no access to most of the neat stuff. About the only hardware-based features that a web app can count on are:

  • Accelerometer orientation changes (e.g., portrait or landscape)

  • Gyroscope motion (iOS 4.2 or later)

  • Multitouch events (e.g., two-finger pinching or stretching)

  • Location services (as many as are supported by the device)

Native apps, however, have substantially more access to the hardware—although not necessarily every piece that developers might like. For example, apps built for devices containing cameras can capture images (and video, where available) to facilitate image editing tasks. Devices equipped with a digital compass expose the current heading of the device. Sound captured by the device’s built-in (or plugged-in) microphone can be recorded and further processed by code inside a native app. An app can read information about the battery state and an iPhone’s proximity detector (which knows when a user has the handset near her face). Native apps can also read from and write to files of their own construction (albeit within some security-driven confines of the directory structure reserved for the app).

Although Apple has begun to expose limited parts of the hardware to web apps (essentially creating objects, properties, and methods that extend the DOM), such exposure lags well behind the range of hardware features waiting to be used by native app developers. I expect more hardware access to come in future iOS versions, but web app access will likely stay several steps behind native app capabilities.

More Access to the Software

On the software side of the iOS, native app development offers a wide range of features that web app developers don’t typically have available. For example, here is a list of software features introduced with iPhone OS 3.0 that are available only to native apps:

  • iPod library access to read library contents and play tracks

  • Displaying interactive embedded Google Maps with many of the same capabilities and identical performance to that of the Maps app

  • Peer-to-peer communications for multiplayer game play

  • Precise control over how cut/copy/paste works in an app

  • Powerful structured data mechanisms ideally suited to displaying lists (the Core Data framework)

  • Precise control over audio recording details (sampling rates, audio formats, etc.)

  • Push notifications to signal users about important events that launch your app

  • Creating and sending email messages from within the app

  • Reading and selecting information from the Contacts app

  • Very powerful OpenGL ES 2.0 3-D graphics composition platform

  • In-app purchases to encourage users to add paid features or extend subscriptions

If that list doesn’t send your imagination into overdrive, perhaps several new native app features of iOS 4 will:

  • Playing audible media while the app is suspended in the multitasking environment

  • Receiving system notifications of changing between active and suspended mode

  • Posting notifications to users at predetermined times, even if the app is suspended

  • Integrating with Calendar app data

  • Displaying revenue-generating advertisements from Apple’s iAd service

It’s not uncommon for native app developers to apply several of these advanced software features (along with hardware features mentioned in the previous section) to augment their apps. For example, one of my own native apps, iFeltThat Earthquake, uses the in-app email feature to make it easy for users to contact me with questions and suggestions about the app. The app also lets users select an entry from their Contacts list to create a geographical center point around which recent earthquake activity is shown (the app uses geocoding to convert a contact’s street address to map coordinates).

All of this native software goodness still allows developers to fold useful web content into a native application. iOS supplies a mechanism for displaying live web content within a native app. The “viewer” used for such web content has all the HTML, CSS, and JavaScript features of Mobile Safari (and its WebKit engine), but without the chrome of the Safari app. You simply define a rectangular viewing region on the screen and supply a URL to the web viewer. In iFeltThat Earthquake, for example, I keep users informed about news and user tips via an HTML-authored page made available from a web server. Each time the app launches, it looks to see if the news web page has been modified since the last visit; if so, it downloads the page, stores a copy on the device, and signals the user that a news flash is available for reading.

I chose to compose the news material in HTML for a couple of reasons. First, as a veteran HTML handcoder, I am, of course, comfortable generating content in that format. It allows for quick composition and easy testing of the page from a local server using Mobile Safari on an iPhone-compatible device. It also means I am free to change the styles (CSS) of the news page without having to update the entire app. The second reason for choosing HTML is that I can easily provide links to other HTML content, whether composed by me or served from a different external source. Because the news page is shown within a web viewer inside the app, links operate as they do in any browser, replacing the current page with the destination of the link. My in-app web viewer provides just a minimum of browser controls for reloading, stopping a load, and back and forward navigation.

In many ways, web development skills are powerful adjuncts to native iOS app development. Being comfortable in both environments means you can call on the right deployment tool for various parts of a native app. Hardcore Objective-C and Cocoa developers might be wary or unaware of the web powers that you have in your hip pocket. Once you master native app development, you’ll have a distinct advantage over your Objective-C-only colleagues.

What You Lose

By and large, the full iOS SDK feature set offers your app designs far more flexibility and the ability to recreate the full range of user interface features you see on Apple’s own apps and apps developed by third parties. But there are costs—in monetary and toil currencies—to obtain those native app powers.

Except for apps designed for in-house corporate use, native apps that run on nonmodified devices—i.e., iPhones and iPads that have not been jailbroken (hacked to allow unapproved third-party apps)—must be distributed via the iTunes App Store. This is both a blessing and, for some, a curse for several reasons.

Distribution

On the one hand, since the App Store is a single point of distribution, all users of unhacked iPhone, iPod touch, and iPad devices go to the App Store in search of apps that will help them scratch an itch. While you may have to choose your app’s description keywords carefully to help potential users search for your product, at least you don’t have to play search engine optimization games to get your app high in search engine results.

On the other hand, the App Store becomes the one-and-only gatekeeper between your app and the consuming public. You must submit your finished app to the App Store for approval before it appears in the store. Approval times can vary widely, often without explanation. Sometimes it’s a matter of only a couple of days; other times it can take weeks. The same is true for updates to existing apps. If you need to issue an update to fix a bug, the approval time can be just as long—and, inexplicably, sometimes longer—to get that maintenance release out to the world. You can apply for an emergency update to help hasten the approval, but if you abuse that privilege, you risk upsetting the gatekeepers.

Apple iOS Developer Program

A prerequisite to submitting a native app to the App Store is an annual paid membership to the iOS (formerly iPhone) Developer Program. The current fee is $99.00 per year. Membership lets you obtain the necessary digital certificates that permit developers to load native apps onto test devices and to upload finished apps to the App Store for approval. You also have access to beta versions of the next version of iOS SDK and iOS software (all under nondisclosure agreements, so you can’t blab about them).

In addition to paying the developer program fee, you must also complete a distribution contract with Apple. For paid applications, the contract process also requires that you establish banking relations with Apple. As with app approvals, the time required to complete the contract varies depending how busy Apple is. It’s not something to leave to the last minute, because it can take several weeks to complete, even longer for developers outside of the United States. Once you pay for the iOS Developer Program, you should begin the contract process, even as you work on your first native app.

Content

As the gatekeeper to “shelf space” on the App Store, Apple’s approval process also imposes restrictions on the content of native apps. Your developer agreements spell out the fundamental guidelines, but Apple inspects each app for compliance on a case-by-case basis.

Such is not the case for web apps. You can serve up whatever you want (within the confines of your own local laws, of course) because the web app is hosted on your server and the device’s owner can freely decide to visit your server or skip it.

If you are already aware that web apps—indeed any content designed to be played through the Mobile Safari browser—cannot avail themselves of Flash or Java, you should also be aware that native apps don’t get you any further with respect to those two software platforms. As of this writing, iOS does not natively support either runtime environment.

Authoring Platform Choices

You can write HTML, CSS, and JavaScript code with a text editor on any operating system platform of virtually any generation. Plain text editing doesn’t even require a graphical user interface, which is why you can find plenty of Unix programmers composing web code in command-line interface editors, such as Emacs and vi (or variants thereof). The key to this flexibility is that conversion to machine code occurs in the web browser. Such is not the case for writing native apps.

Developing native iOS apps requires Apple’s integrated development environment (IDE) called Xcode (pronounced EKS-code). Even though Windows users can sync their iOS devices to their PCs via iTunes for Windows, the Xcode IDE is available only for Macintosh computers.

Taking the Plunge

Beginning with the next chapter, you will see the changes to the development process and programming environment that you will have to adopt to develop native apps. Some of the changes are radical, so if you jump into the programming environment cold, the transition will seem overwhelming. But, just as you learned the intricacies of CSS, JavaScript, and the DOM, the same will happen with iOS SDK development with practice and experience: throughout this book, you’ll learn new concepts that build upon one another. My purpose here is to help you embrace that transition by putting new items in the context of your existing knowledge.

Let’s get started.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required