|
Now that you’ve learned how to code iPhone web pages in a variety of ways, you’re probably ready to dive right in. But as we discussed in the last chapter, programming great iPhone web pages isn’t just about using the right libraries, it’s about using the right tools as well. In chapter 7, we discussed a specific tool, the Dashcode development platform. Now we’re going to look at some more general tools that can be used to test and debug a variety of programs. We’ll begin with the most fundamental tool of all: the Apache web server.
If you have a Mac OS X computer, you can take advantage of its built-in Apache web server to quickly prototype and test web pages. Setting it up is a simple process, as outlined in table 8.1.
Description |
|
---|---|
1. Start up your web server. |
From the Apple menu, choose System Preferences. Click the Sharing icon. Select the Web Sharing checkbox. |
2. Share files. |
Create files with a plain text editor, such as Emacs, which can be accessed from the Terminal. Move the files to the Sites folder in your directory. |
3. Test. |
Visit your web pages from your Mac at http://127.0.0.1/~YourUsername/Test, test, test. |
The benefit of developing and testing your web pages locally is that you can do so without affecting your live pages. Further, since Mac OS X is essentially a Unix system, you can set up your local system to mimic your web server as closely as you’d like. With just a few minutes of work, Shannon was able to set up his own test page, which we’ve used to double-check a lot of the web code in this book. This was the URL:
http://127.0.0.1/~Shannon Appelcline/test.html
After you’ve viewed a web page from your local machine and seen that it generally works, you’ll probably want to test things from your iPhone as well (though, as we’ll see, the iPhone Simulator is another option). This can be done by replacing the 127.0.0.1 in the previous URL with the actual IP address of your machine. You can find your IP address by clicking Network under System Preferences in the Apple menu. You also might need to make one other change when typing your test URL into your iPhone. If you have a username with a space in it, as Shannon did, you’ll need to replace that space with “%20” (the correct symbol for a space in a URL) when you type it into the iPhone. Here is the alternative URL that we used for our test machine:
http://192.168.1.100/~Shannon%20Appelcline/test.html
Though we haven’t talked about any actual debugging techniques yet, using your local Apache web server will make using any debugging techniques quick and easy.
Once you’ve got a local server in place, you can use your desktop browser to see how your iPhone web pages really work. On the Macintosh you’ve got three great choices—Safari, Firefox, and the iPhone Simulator. Each has its own debugging advantages.
On a Macintosh, your default browser will be Safari (unless you’ve changed it). Like most modern browsers, Safari comes with built-in development tools. You can find them under the Develop menu. If the Develop menu doesn’t appear, you can activate it in the Safari preferences: choose the Advanced tab, and check the “Show Develop menu in menu bar” check box. Once you’ve done that, you’ll see a menu full of cool features, beginning with the Web Inspector.
The Web Inspector is the main element of Safari’s debugging system. It’ll show you the code underlying your web page, including stylesheets, images, and script files. Most importantly for programmers working with the WebKit, you can also look up the contents of client-side databases, as shown in figure 8.1.
Within the Web Inspector, you’ll find two other tools: the Error Console and the Network Timeline. The console shows you errors in JavaScript; it’s what you need when you’re using Canvas to create graphical web apps. Also note that this console replaces Drosera, the JavaScript debugger that was previously available under Safari. The timeline will list all the individual files used by a page and show you how long each takes to load. It’s terrific for when you’re trying to decrease load time for mobile devices.
Back on the Develop menu there’s one other cool feature, the User Agent utility. It causes the browser to send a different user agent to the server, thus pretending it’s a different type of browser. If you want, you can have it pretend to be mobile Safari. It even differentiates between the iPhone and the iPod Touch. We generally suggest using the iPhone Simulator instead (and we’ll return to it shortly), but differentiating between those two devices can occasionally be of use.
Though you might be content to stop with Safari, it’s by no means the only browser option that you have under Mac OS X.
Though we should perhaps remain loyal to Apple software in this book, we’ve found Firefox to be an even stronger platform for web page development, mainly due to its robust and well-supported add-on system. Table 8.2 lists the current places to download Firefox and the add-ons that we like best for web development.
Program |
Location |
---|---|
Firefox |
|
DOM Inspector |
|
Web Developer add-on |
|
Firebug add-on |
Firefox ships with a JavaScript Error Console that seems to provide slightly better and more detailed information than Safari, as shown in the comparison in figure 8.2. Prior to version 3 of Firefox, a DOM Inspector shipped with the browser. It provided more architectural info than Safari’s similar Web Inspector, but less info on the files that make up a page (and no info on databases!). Now it’s available as an add-on. Firefox notably has no built-in tool to let you see how long your page takes to download.
Firefox really shines when you install Chris Pederick’s Web Developer add-on. This gives you access to a menu and optional toolbar that provide you with a huge array of information about the web page you’re viewing.
We find the forms functions—which allow you to see exactly what variables are holding what values in your forms—and the outline functions—one of which lets you outline table cells, so you can see exactly how they’re built—to be the most useful features. There are also CSS-related functions, a variety of validators, and a lot more. And yes, there’s a Speed Report too, though it depends upon an external service to work.
Firebug is another great add-on for Firefox. It’s by iUI developer Joe Hewitt, and it gives you an in-depth look at all of a page’s code. Whereas Web Developer is more about how things look, Firebug is more about how they work. There’s some overlap, but the two make a good combination. Besides providing data on things like the DOM, CSS, and what headers look like on the internet, Firebug also provides a great console object that gives you a variety of tools for debugging.
After you install Firebug, you can activate it at any time by choosing Open Firebug from among your Firefox tools. When you do that, a panel will appear along the bottom of the screen. Most of the tabs provide you with the information that we’ve already discussed. It’s the Console tab that bears further discussion.
First of all, the command line at the bottom, marked by “>>>”, gives you the ability to enter raw JavaScript commands that will be executed immediately. Figure 8.3 shows how easy it is to play around with Canvas by adding a new Bezier curve to our final Canvas example from chapter 6.
The Firebug console also has another great feature: it introduces a new console JavaScript object that can be used to aid JavaScript debugging in various ways. Some of the most important console methods are listed in table 8.3.
Method |
Summary |
---|---|
console.log |
Writes text to the Firebug console. May include variables for strings (%s), numbers (%i or %d), floating-point numbers (%f), and object hyperlinks (%o). Variant methods console.debug, console.info, console.warn, and console.error similarly write text to the Firebug console, but with different emphasis. |
console.assert |
Tests whether an expression is true, and, if not, writes to the console. |
console.dir |
Creates a listing for an object, identical to the Firebug DOM info. |
console.dirxml |
Creates an XML listing for an object, identical to the Firebug HTML info. |
console.profile |
Encapsulates the JavaScript profiler when used with console.profileEnd. |
console.trace |
Creates a JavaScript stack trace. |
The console methods can be called from within your JavaScript functions. Information will then be reported directly to your Firebug console when you view your page from Firefox:
console.log("Starting JavaScript Execution!");
Our listing of console methods is by no means exhaustive. Firebug also provides over a dozen special functions that are available only from your console command line and that may be used to monitor events, look at objects, profile code segments, and otherwise figure out how your JavaScript is working. An in-depth look at these topics is beyond the scope of this book, but the Firebug website has great documentation on the console and the command-line options alike.
As a result of all these features, Firebug should be your first stop when you’re doing Canvas work or any other type of JavaScript coding. But what if you really need to see precisely how something looks on an iPhone? If you’re working on a Macintosh, you can just open a new window to solve this problem as well.
As we’ve mentioned several times, Apple provides an iPhone Simulator for the Macintosh. All of the screenshots of the iPhone in this book come from the iPhone Simulator, captured with Apple’s Grab utility.
The iPhone Simulator comes as part of the iPhone SDK, but even if you’re not planning to do any SDK programming, it might be worth getting the current version of the SDK (though the download is quite large, at over 1 GB at the time of this writing). We’ll talk more about what all is in the SDK package (and how to get it) in chapter 10.
The iPhone Simulator doesn’t come with any additional development tools, like the other browsers we’ve been talking about, but it provides the most precise simulation of an iPhone that you’ll find, other than using the iPhone itself (and though we both have iPhones sitting right on our desks, hooked up to our computers, we still find it faster to pop up the Simulator, even to test out a simple web page, let alone SDK programs that require downloading).
Besides looking at pages on your iPhone Simulator, you can also rotate the iPhone left or right using the arrows keys. Perhaps most importantly, you can simulate two-finger gestures by holding down the option key when you scroll over the Simulator. Option-shift will additionally lock these fingers in relation to each other, allowing you to generate a two-fingered scroll event.
Seeing exactly what things look like on an iPhone should help you quickly resolve many purely visual problems with your iPhone web code. With that said, we’re going to leave servers and browsers behind, and instead move on to more in-depth debugging tools.
Desktop programs are generally the best way to debug your iPhone web apps. That’s because you can have a fully featured desktop browser sitting next to an iPhone Simulator. With the first, you can easily look at source and use any number of development tools, and with the second you can look at how something appears on the iPhone.
Conversely, debugging on the iPhone itself can be more troublesome. Not only don’t you have those development tools, but you can’t even look at the source code! You’ll be falling back to using alert()s for debugging purposes, and you’ll be heading back to your desktop anyway to read and modify code. So, especially if you have access to the iPhone Simulator, our best advice for debugging directly with your iPhone is: don’t do it.
Despite that admonition, you might have to if you don’t have access to a Mac or if the iPhone Simulator and the actual iPhone aren’t showing the same results (though we’ve only seen a difference thus far on websites that used too precise an agent lookup when trying to discover if you were using an iPhone). In these situations, there are a few tips and tricks likely to help you out. We’ll be referring to two freeware programs within this section, both of which are listed in table 8.4.
Program |
Location |
---|---|
iPhone Debug |
|
iPhone Web Developer |
Of these two programs, the first is intended specifically for JavaScript debugging, while the second—which we’ll meet as part of a larger discussion of bookmarklets shortly—supports more general HTML debugging. We will not be discussing a third tool, Firebug on the iPhone, because it stopped working when iPhone OS 2.0 was released, with no indication that it’s going to be repaired in the future.
Jon Brisbin’s iPhone Debug is a JavaScript debugging program. He explained the need for the new tool by saying:
The complete installation instructions are listed at the iPhone Debug website. They’re complex enough that they’re likely to change through additional revisions, so we haven’t repeated them here.
Generally, iPhone Debug provides you with similar functionality to the desktop Firebug, centering around a desktop console that you can use to receive data about a page you’re viewing on your iPhone.
iPhone Debug is great for troubleshooting JavaScript code on your iPhone, but you may also want to debug plain HTML—possibly when you don’t have a desktop computer available. For this situation, there’s one more tool that you might find useful: bookmarklets.
The word bookmarklet comes from combining the words bookmark and applet. They’re little bits of JavaScript code that are encoded as URLs. Thus, when you see a mini-application that you like, you save it as a bookmark, and then you can activate it at any time just by selecting the appropriate link from your bookmark list.
For the iPhone, bookmarklets can give you all the client-side functionality that you want but don’t have access to: things like viewing source, and using client-side tools like those found in Firefox and Safari.
Listing 8.1 shows code that will view the source of a page, written by Erwin Harte based on original code by Abe Fettig.
var sourceWindow = window.open("about:blank");
var newDoc = sourceWindow.document;
newDoc.open();
newDoc.write("<html><head><title>Source of " + document.location.href +
"</title><meta name="viewport" id="viewport"
content="initial-scale=1.0;" + "user-scalable=0; maximum-scale=0.6667;
width=480"/><script>function do_onload()" +
"{setTimeout(function(){window.scrollTo(0,1);},100);}
if(navigator.userAgent.indexOf" + "("iPhone")!=-1)
window.onload=do_onload;</script></head><body></body></html>");
newDoc.close(); var pre =
newDoc.body.appendChild(newDoc.createElement("pre"));
pre.appendChild(newDoc.createTextNode(
document.documentElement.innerHTML));
The code itself is basic JavaScript, and we won’t go too far into the details. When clicked, this bookmarklet jumps to a brand new window that contains the entire text of the web page as a <pre> element. There’s also a tiny bit of magic to scroll the chrome on an iPhone, solely for aesthetic purposes. In order to turn this code into a bookmarklet, you just need to urlencode() it so that the JavaScript is properly formatted as a URL.
You can create whatever bookmarklets you want, to add functionality to your iPhone. But there’s already a large collection of them available at the iPhone Web Developer site listed in table 8.4. To use that site, browse to it on your desktop Safari, adding the bookmarklets that you like to your bookmarks menu. Then you sync your Safari bookmarks to your iPhone through iTunes, and you’ll have instant access to the Web Developer bookmarks that you wanted.
Having now looked at several ways in which you can make your iPhone web pages work correctly, we’re going to finish up with a look at how they can work better.
Profiling—or performance analysis—is important for any type of computer program. But we’ve gotten sloppy about profiling web pages in the last several years as bandwidth has gotten cheaper and more abundant. With the iPhone, we now need to sit up and start paying attention again. This is because of some of the unique features of the iPhone.
We’ve already touched several times upon the fact that an iPhone in the wild depends upon the EDGE or 3G network for downloading. This means that we have to create smaller, leaner pages. But we also always need to remember that one of the iPhone’s unique features is its energy consciousness, and as a result we shouldn’t be creating web pages that take more juice than they need.
Solving the bandwidth problem is an easy one, because there are lots of tools available to help out, such as Safari’s Network Timeline, which shows where your web page is getting slowed down. Generally, when analyzing bandwidth you should try to remember the low-bandwidth lessons of yesteryear, including the following:
Besides showing you how long files are taking to load, the Network Timeline might also remind you of files that you hadn’t even realized were being loaded, and thus are slowing you down for no reason.
Solving the energy problem is more difficult only because it’s not an issue you usually have to think about when creating pages for desktop use. The top thing you need to watch is JavaScript. You don’t want to include timeouts or event handlers that are constantly going to go out to the network or engage in other high-cost activities. Generally, you should think carefully before putting any sort of infinite loop on a page that’s going to be viewed by an iPhone. It might be OK for an animation or some other client-side activity that will quietly shut off when the phone goes to sleep, but you should make sure you’re polite about anything more than that. You don’t want users avoiding your iPhone website because you drained their batteries.
The general lesson for iPhone profiling is this: pay attention and write the sort of carefully considered code that you were probably thinking more about in the 1990s, before bandwidth and CPU became cheap.
Lessons for SDK developers
In all honesty, we don’t have much for you SDK developers this time. Most of our discussion in this chapter was about web servers and clients, and clearly those are going to have little crossover with SDK development. The only point of particular relevance is the section on iPhone profiling.
Thinking about energy consciousness is going to be even more important when we get into SDK development. There’s a limit to how much damage a web programmer can do, because the iPhone ultimately controls access through the Safari interface. On the other hand, as an SDK programmer you’re going to have access to a lot more fundamental code. Apple has done what it can to keep native programs from gobbling up an iPhone’s battery, but you’re going to need to do your part too.
Over the past six chapters, we’ve covered the libraries and tools that you can use to write iPhone web pages, but we’ve also done our best to show standard iPhone architectures in the process. Generally, it all comes down to understanding the iPhone’s key features. Knowing them and what they mean is as important to writing iPhone code as the actual features and functions we’ve been discussing.
An always-on internet is the thing that allows us to write web apps, and, as we’ve just seen, power consciousness is an important consideration in profiling. The iPhone’s unique input and output have been relevant to almost everything we’ve talked about in writing web pages, while its orientation awareness has occasionally been both an issue and an opportunity. The iPhone’s location awareness is the only topic we haven’t been able to look at when thinking about web applications, because that information isn’t available yet to the web developer.
In this chapter, we’re offered our best advice on how to make the web programming that you’re doing easier. But the internet is a huge place increasingly full of great open source software and freeware. It’s entirely possible that you’ve already found tools that you like better than the ones we’ve suggested.
Now that we’ve finished with our overview of the web, we invite you to take some time to get used to how the iPhone works in its web incarnation. Web programs will always remain among the easiest and most accessible programs that you can create for the iPhone, thanks to the simplicity of the web-based languages that have been developed over the last 15 years. As we discussed in chapter 2, even if you move on to the SDK, we believe that web programming will continue to have its place.
But we also hope that you’ll eventually be champing at the bit to do more: that you’ll want to get into the guts of the iPhone and learn how to create native applications that can better utilize the iPhone’s unique features and that can run with or without access to a network. For that reason, we invite you to move on to part 3 of this book, which explores the flip side of iPhone programming: the SDK. To help you get there, we’ve written a special chapter intended to help bootstrap web developers into Objective-C coders; that’s up next.
3.138.116.228