Tài liệu Lập trình ứng dụng cho iPhone part 4 - Pdf 98

55
Advanced WebKit
and textual web apps
In the previous chapter we covered the fundamentals of redeveloping an existing
web page for use on iPhones. In the process you learned about important concepts
like the viewport, and we discussed a lot of what works—and what doesn’t—on
Apple’s unique mobile platform. We expect, though, that most of you aren’t just
interested in touching up existing web pages but instead are looking to create
totally new programs. Further, after considering the advantages and disadvantages
of both web and native development, you’ve decided that writing a new program
using a web language is the best way to go. We’re now ready to enter the world of
web apps, a topic that will consume the rest of part 2 of this book.
We’ve identified three ways to create web apps for the iPhone. Each will take
advantage of all your existing web knowledge, but each will also connect you with a
specific library or Apple browser add-on that will allow you to unlock additional
functionality on the iPhone platform.
This chapter covers

Learning about the WebKit

Recognizing touch gestures

Recognizing orientation
56 CHAPTER 4 Advanced WebKit and textual web apps
First, you might choose to build a textual web app, which is an application that is
largely built on the fundamentals of
HTML itself. You’ll be able to supplement it with
the advanced features of Apple’s WebKit. We’ll be discussing this programming
method in this chapter.
Second, you might choose to build an iPhone-
UI web app, which is an application

WebKit compatibility note
Although we’re highlighting the WebKit for the advanced functionality it offers to the
Apple iPhone, you can make greater use of the features in this chapter that are not
iPhone specific. This includes new tags, various sorts of animation, and the client-
side database. Most notably, these features should work on Apple’s desktop Safari,
the brand-new Google Android and Google Chrome platforms, and GNOME’s Epiphany
browser. Many of these features will become more accessible when they’re accepted
into new HTML and CSS standards.
57Introducing the WebKit
We’ll offer the warning that all of this functionality is very new. Since some of the
functions are being offered for future HTML and CSS standards, they could change
entirely. Even now they’re not entirely consistent. Over the course of writing this chap-
ter we discovered one minor function (a transitioning rotation) that worked on Safari
but not mobile Safari and a whole category of functionality (explicit animation) that
worked on mobile Safari, but nowhere else. We expect that by the time this book is
published, behavior will be more consistent across versions of Safari, but our prime
goal has been to document how things will work on the iPhone.
4.1.1 New HTML elements
The WebKit introduces several new HTML elements. We’ve listed the ones most likely
to be useful for iPhone design in table 4.1.
There are also some variants of
<pre>
and some alternate ways to do embeds and lay-
ers, most of which are being deprecated in HTML 4.01.
4.1.2 New CSS elements
The bulk of the WebKit’s new functionality comes from its large set of extensions to
the CSS standards. These include the full set of transforms, transitions, and anima-
tions that we cover separately later in this chapter, as well as some simpler
CSS ele-
ments that are summarized in table 4.2.

There are not only other
CSS properties, but also
new CSS constants that can be applied to existing
properties. Our main purpose is to show you the
cooler elements that are available among the
WebKit’s basic
CSS elements, and to encourage
you to find out more information at Apple’s
WebApps reference site.
Figure 4.1 shows how some of the new WebKit
CSS properties could be applied to a simple
<div>
to create an attractive box that features rounded
corners and a three-dimensional back shadow.
The
<div>
is simply defined with a new class
name, as is typical for
CSS:
<div class="roundedbox">
The definition of the roundedbox class then
includes several standard CSS properties (to set
Box -webkit-box-shadow
Sets a drop shadow for a box by designat-
ing a horizontal offset, a vertical offset, a
blur radius, and a color.
Link -webkit-tap-highlight-color
Overrides the standard highlight when a
user taps on a link on an iPhone.
Link -webkit-touch-callout

59CSS transforms, transitions, and animations
the background-color and so forth), plus the new border-radius and box-shadow
properties, which appear for the first time in Apple’s WebKit.
The code to create the
roundedbox
class is shown in listing 4.1.
.roundedbox {
background-color: #bbbbee;
border: 1px solid #000;
padding: 10px;
-webkit-border-radius: 8px;
-webkit-box-shadow: 6px 6px 5px #333333;
}
All of the other new CSS properties could be used in a similar way.
THE IPHONE-SPECIFIC PROPERTIES
Before we finish our discussion of the simpler WebKit CSS properties, we’d like to
point out the ones specifically intended for the iPhone.
–webkit-tap-highlight-
color
and
–webkit-touch-callout
each give you some control over how links work
on the iPhone. It’s the last iPhone-specific property,
–webkit-text-size-adjust
, that
is of particular note, because it allows you to increase point size by a percentage only
on the iPhone.
In chapter 3, we talked a bit about adjusting font sizes through multiple
CSS files.
However, if that’s all you need to do differently between iPhones and desktop brows-

class from listing 4.1,
turning it into a
wackybox
class:
-webkit-transform: rotate(30deg) translate(5%,5%);
The result is that your news article appears at an angle, moved somewhat off the screen.
Figure 4.2 shows this change, which you can compare to the nontransformed news article
that appears a few pages back as figure 4.1. This particular transform isn’t that useful if
you want people to read it, but it could be
a nice background for a news site or
something similar. There are many other
things that you can do with transforms,
such as setting up banners, printing text
at a variety of sizes, and making similar
changes on static web pages. Some will be
gimmicks, but others can have func-
tional benefits.
Before we leave transforms behind,
we’ll note that they support one other
property,
–webkit-transform-origin
,
which can be used to move the origin for
scales and skews away from the center of
the object.
Although you can do quite a bit with
transforms all on their own, their real
power appears when you start working
with the implicit animation of transi-
tions, which are the next WebKit func-

properties in the
CSS element that marks the end of your animation. You can define what properties to
transition (possibly including all of them), how long the transition should last, and
how the transition should work. Then, when the block of text changes to the end-
point class, a smooth and animated transition will occur. Table 4.4 lists the various
transition properties.
Unfortunately, not all
CSS properties can be transitioned. Apple states that “any CSS
property which accepts values that are numbers, lengths, percentages or colors can be
animated.” This isn’t entirely true, because some percentage-based elements such as
font-size
don’t yet work. If you want to know whether a CSS property can be transi-
tioned, you can find a list on the Apple website. And there’s no harm if you list some-
thing that doesn’t transition in a property; it just does an abrupt change instead.
You can reduce a transition command to a single line of code using the
–webkit-
transition
shorthand property:
-webkit-transition: property duration timing-function delay
Separate additional transitions after the first with commas.
Traditional websites are already making good use of transitions to highlight page
elements when a hover occurs. However, hovers aren’t possible on the iPhone, so it’s
more likely that you’ll be making transitions based on a click. Listing 4.2 shows a sim-
ple transition of a box to color in the text and background (making it more visible)
when you click it.
div {
-webkit-transition: all 2s;
}
Table 4.4 Transitions let you animate changes of CSS properties.
Property Values Summary

.visiblebox {
background-color: #bbbbee;
opacity: 1;
// Other properties make our box beautiful
}
Once you’ve defined these styles, you just need to add an
onclick
event handler that
shifts from one style to the other:
<div class="clearbox" onclick="this.className='visiblebox'">
This simple transition could easily be built into a more sophisticated interface where a
user could make individual elements of your page more or less visible by clicking on
those individual elements (or alternatively through some pagewide control panel).
Seeing this simple example highlights why transitions are called implicit animation.
You don’t have to do a thing other than define your endpoint styles and say what you
want to animate between them. In this example, your pages enjoy a nice animation
from gray to cyan, with increasing opacity, thanks just to your defining two styles (and
a transition for all
<div>
s).
However, transitioning between normal styles is just the tip of the iceberg. The
coolest thing about transitions is that they can be used with that other new WebKit fea-
ture we just discussed: transforms.
TRANSITIONING TRANSFORMS
By putting together transforms and transitions, you can create actual graphical anima-
tions of scales, rotates, skews, and translations. In other words, you can make boxes
revolve, move, and otherwise change, showing off sophisticated graphical animations,
with nothing but
CSS definitions (and perhaps a bit of JavaScript to change the styles).
Listing 4.3 shows how to put a transition and a transform together to create an ani-

<div id="mydiv" class="imagebox"
onclick="animatePic(this.style);">
<img src="cat.jpg">
</div>
</body>
</head>
For the example in listing 4.3, your transforms are enacted in JavaScript. Therefore,
your CSS file only needs to do two things. First, you set up all
<div>
s so that they’ll tran-
sition
B
, and second, you set the initial scale of your images to be .2
C
, which means
that your images will be read in at full size but then displayed in a much smaller form.
Your
<div>
is then set up to use the
imagebox
class and call the
animatePic
func-
tion when clicked
G
.
animatePic
does all the magic
D
. Every other click, it either

-webkit-animation-name: 'moveit';
-webkit-animation-duration: 5s;
-webkit-animation-iteration-count: 1;
}
@-webkit-keyframes 'moveit' {
0% {
left: 0px;
top: 0px;
}
20% {
left: 0px;
top: 100px;
}
100% {
left: 0px;
top: 450px;
opacity: 0;
}
}
To create an animation, you must define a style
B
that includes a set of
–webkit-
animation
properties. The three critical ones are
–webkit-animation-name

C
, which
is the name for the animation;

other event occurs. For example, if a button in your application requires a double-
click, you could start the button shivering when it’s clicked the first time to encourage
a second click.
Our simple example here just takes a box and shoves it down toward the bottom of
the screen, making it disappear as it goes. You could use similar functionality to delete
items from a page as a user interacts with it.
The transformations, transitions, and animations are all impressive when put into
use. However, there’s one more WebKit function that’s broadly available on WebKit
browsers that we think is even more impressive—and more likely to be useful in your
own web apps: the client-side database.
4.3 The WebKit database
WebKit includes a client-side database built on SQLite. This means that you can save
much larger amounts on information on your client’s machine—which could be an
iPhone—than was possible using traditional cookies. This is all done through a set of
new JavaScript routines.
4.3.1 Loading a database
A table is loaded into your JavaScript through the openDatabase command:
var mydb = openDatabase(databaseName,version,displayName,maxSize);
databaseName
and
displayName
are both arbitrary names that you’ll select for an indi-
vidual database.
version
should currently be set to
1.0
, and
maxSize
is a maximum
size for your database in bytes (such as

results
and
error
are both fully featured JavaScript objects that give you access to a
number of properties and let you know how your
SQL query affected your database.
The most important ones are listed in table 4.6.
The underlying functionality of the JavaScript database is quite simple—presuming
you already know
SQL. Thus the question becomes: how can you use it?
4.3.3 A sample database
A client-side database will have any number of advantages, all of which you can make
use of on the iPhone. However, there’s one iPhone-specific trick you should consider:
iPhones uniquely might be connected to either a fast network (wireless) or a slow net-
work (
EDGE or 3G). So why not give your users the ability to offload their networked
Table 4.5 Error and data handlers tell you what SQLite is doing.
Function Arguments Notes
dataHandler transaction, results
Parses results of successful query
errorHandler transaction, error
Shows query errors
transactionError error
Runs if anything in transaction failed
transactionSuccess
N/A Runs if everything in transaction succeeded
Table 4.6
error and results give you access to SQL responses.
Property Summary
error.code

function updateBooks() {
// Clever code to pull data from your website database goes here
myDB.transaction(
function(transaction) {
transaction.executeSql('DELETE FROM books WHERE 1',
[],nullDataHandler,defErrorHandler);
transaction.executeSql('INSERT INTO books
(btitle,bauthor,bpublisher) VALUES (?,?,?)',
[btitle,bauthor,bpublisher],nullDataHandler,defErrorHandler);
// other transactions go here, as you read out of your website database

}
) ;
listBooks();
}
function listBooks() {
myDB.transaction(
function(transaction) {
transaction.executeSql('SELECT * FROM books WHERE 1 ORDER BY
bpublisher,btitle',[],bookDataHandler,defErrorHandler);
}
) ;
}
function bookDataHandler(transaction,results) {
Listing 4.5 A database that saves online data to a local resource
B
C
D
E
F

C
. Note that
you link to your first two query handlers here. Your default error handler
D
, which
you use throughout this program, just reports your error, while your default data han-
dler
E
doesn’t do anything because most of your queries won’t return any results.
We opted not to use the bigger picture transaction handlers at all. Your individual
project should determine whether or not you need them.
Your
updateBooks
function
F
will change the most at your individual site, since
this is where you need to read the data from your server-side database and dump it
into a client-side database. This function just shows an example of placing one item in
the database, using question marks to highlight how the transaction’s array argument
works. You’ll doubtless have some type of
for
loop in a real program to iteratively map
your data into the client-side database.
When you update the books, you also list them
G
, which ultimately updates the
data on your web page. This is the only
SQL transaction that uses a real data handler, a
requirement since it returns results.
Your

The JavaScript database is the last WebKit element
that you can make use of on the iPhone, but it can also
be used more broadly. The last couple of items that
we’ll discuss are instead iPhone specific.
4.4 Adjusting the chrome
In the previous chapter we showed you some simple
methods for dealing with the iPhone chrome. We
explained how to scroll the
URL bar and noted that the
status bar and the bottom bar could not be changed.
Using the WebKit, you have slightly more control over
things, provided that your user is using iPhone
OS 2.1
or higher. All you need to do is enter a new metatag on
your web app’s home page:
<meta name="apple-mobile-web-app-capable" content="yes" />
This code doesn’t change the web app when it’s run through the browser. It’s only
when a user chooses to save your app to his or her iPhone home page and then calls it
back up that things will act differently. When called back up, your app will appear
without the
URL bar or the bottom bar: only the status bar continues to eat space in
your web app.
Because your user will not be able to navigate using the
URL bar, you have to be
very careful when using this metatag. You should only do so when navigation is totally
self-contained within the program—for example, if you’ve built it with i
UI or Dash-
code, both topics that we’ll return to in future chapters. This metatag is only appropri-
ate for a true web app.
There’s one other metatag of note:

To facilitate ease of use, the WebKit also introduces an abstraction that you won’t
find in the
SDK: the gesture. A gesture begins when two or more fingers touch the
screen and ends when there are one or zero fingers left. Like touches, gestures are
collected together into events.
4.5.1 Accessing events
Based on its standard touch and gesture models, the WebKit recognizes seven Docu-
ment Object Model (DOM) event classes, as shown in table 4.7.
Depending on the complexity of input desired, you may use gestures or touches, or
possibly both, in your website. We’ll look at both gestures and touches in this section,
and you’ll see some of the amazing things you can do when you combine them with
other WebKit functions.
ACCESSING AN EVENT
You can access any of these new touch events by one of two methods, as you can with
other events in
HTML. First, you can link an event handler as part of an object’s HTML
definition:
<div ontouchstart="myTouchStart(event);">
Table 4.7 With touches and gestures, you can recognize iPhone touchscreen events.
Event Summary
touchstart
A finger touches the iPhone.
touchmove
A finger moves across the iPhone.
touchend
A finger leaves the iPhone.
touchcancel
The system cancels a touch.
gesturestart
Two or more fingers touch the iPhone.

and
touchmove
events if you’re looking at touches. If you’re looking at gestures, you’ll probably have to
run
preventDefault()
for
gesturestart
and
gesturechange
events.
4.5.2 Converting events
Whether you’re using the touch or gesture events, you’re going to need to convert
those events into individual touches in order to use them. You accomplish this by
accessing a number of properties of the event object, as listed in table 4.8.
Note that
changedTouches
,
targetTouches
, and
touches
each contain subtly differ-
ent lists of touches.
targetTouches
and
touches
each contain a list of fingers that are
currently on the screen, but
changedTouches
lists only the last touch that occurred.
This is important if you’re working with the

rently being stored.
We’ll see this all in use in the next couple of examples.
4.5.3 Accessing touches
Once you’re looking at an individual touch, by using a variable like
event.touches[0]
or
event.targetTouches[0]
you can access additional properties of that touch as
shown in table 4.9.
The majority of these properties tell you where on a page a touch occurred, using a
variety of different X,Y coordinate systems. Putting this together with the basic event
information we’ve already discussed, you can begin to build sophisticated programs
that track where a user is touching the screen and take appropriate actions based on
that information.
Listing 4.6 shows an example of a simple touch-based program that allows you to
drag a color from one box into another.
<html>
<script type="text/javascript" charset="utf-8">
function colorStart(event) {
event.preventDefault();
}
function colorMove(event) {
event.preventDefault();
}
function colorEnd(event) {
if (event.changedTouches[0].pageX > 110) {
document.getElementById('colorbox').style.backgroundColor
Table 4.9 Touch properties contain specific information about a touch.
Property Summary
clientX or clientY

<div id="colorbox" class="colorbox"></div>
</body>
</html>
What’s impressive about listing 4.6 is how little work was required to interpret touch
commands. You start off with a set of
<div>
s—three RGB-colored boxes
E
, which are
small boxes filled with the named color, and a special
colorbox

F
, which is another
small box, this one located at 110x60, which can be filled with the color in question.
The layout information for all of these boxes is contained in styles
D
, which we’ve
opted to leave out since they’re pretty simple
CSS, though we’ve shown the results in
figure 4.5.
Each of the three
RGB boxes refers to three touch-
related event handlers. When touches start or move
B
,
the only thing that happens is that the default behavior
is prevented, so that scrolling doesn’t occur. All of the
code in your program instead occurs in the
touchend

Unfortunately, unlike with the SDK, there isn’t yet a sophisticated manner to mea-
sure which object contains a particular touch; we hope to see that in future releases.
4.5.4 Accessing gestures
Having now worked with touches, you’ll find the WebKit’s gestures are quite easy to
use. Essentially, they work identically to touches, but the events trigger only when
there are at least two fingers on the screen.
Gestures also have a huge advantage: the WebKit does its best to measure two-
fingered pinches and rotations for you. This is done through a pair of two new event
properties that only appear for gestures, as described in table 4.10.
These new properties can allow for simple manipulation of objects using relatively
complex gestures. To demonstrate, let’s expand our coloring example by allowing the
user to scale and rotate the box that’s being filled in.
This new example begins by adding a set of four event handlers to the
colorbox
:
<div id="colorbox" class="colorbox" ongesturestart="boxStart(event)"
ongesturechange="boxChange(event)" ontouchstart="colorStart(event)"
ontouchmove="colorMove(event)"></div>
We’ve reused the touch start and move handlers, because they just prevent the default
behavior, and thus ensure that scrolling won’t occur after users put their first finger
on the screen. The gesture handlers, which are all new, are shown in listing 4.7.
function boxStart(event) {
event.preventDefault();
}
var origAngle = 0;
var origScale = 1;
function boxChange(event) {
event.preventDefault();
event.target.style.webkitTransform = 'scale(' + event.scale + origScale
+ ') rotate(' + event.rotation + origAngle + 'deg)';

new properties to event objects.
75Recognizing orientation
This complex function is easy to write because the WebKit provides you with the
movement information of the gesture, rather than you having to figure it out yourself.
4.6 Recognizing orientation
The iPhone supports two different types of gestures. Touching the screen is what
more immediately comes to mind when you think about user input, but moving the
iPhone around—as measured by the accelerometers—is another way in which users
can manipulate their iPhone. If you need precise accelerometer data, you’ll have to
design using the
SDK (as discussed in chapter 17), but with the WebKit you can at least
recognize orientation changes.
The
orientationchange
event notifies you when a user has rotated the iPhone
after your web page has loaded. Besides just notifying you that an orientation change
has occurred, the iPhone maintains a special
orientation
property in the
window
object that advises you of the iPhone’s current orientation, as described in table 4.11.
Listing 4.8 shows how simple it is to detect an orientation change and take an action
based on it.
<head>
<meta name="viewport" content="width = 200">
<script type="text/javascript">
window.onorientationchange = function() {
document.getElementById("orAnnounce").innerText
= window.orientation;
}

, which is set to the
starting value at startup
D
. Changing a CSS file or some other minor element would
be equally easy. If you’d like to see a more attractive, graphical version of this, we
point you toward the first example of chapter 7, where we use Dashcode to create a
more attractive orientation reporter.
If you wanted to, you could do even more than some simple outputs or
CSS changes.
The authors maintain a sample chat program at
that totally redesigns itself. In portrait mode it shows only a chat window, but in land-
scape mode it also shows a list of users online. You can see a bit less of the conversation
in landscape mode, but what’s there is equally readable thanks to the increased width
of the screen.
Alternatively, you could use an orientation change as a standard user-input device.
A drum machine, for example, could offer a beat whenever the phone is rotated.
The orientation event is the last major WebKit element at the time of this writing.
There’s also some neat upcoming stuff that we want to highlight, since it may be avail-
able by the time this book sees publication.
4.7 Upcoming features: CSS gradients and masks
The WebKit is constantly growing, and in upcoming years you’ll be able to build an
increasing number of great features into your iPhone web pages that won’t be avail-
able to non-WebKit browsers. It can sometimes take a while for new features to make it
from the WebKit “nightly builds” into an actual release from Apple, however.
This is the case with two interesting new graphical features that were announced in
April 2008: gradients and masks. We have faith that both of these new
CSS properties
will soon be available in Safari and on the iPhone, but as of this writing they’re not yet
available. Therefore, we’re just going to cover them in passing, with no guarantees
that the properties will be quite the same when they actually appear.

should work:
.linear {
background: -webkit-gradient(linear, left top, left bottom,
from(#00abeb), to(#fff), color-stop(0.5, #fff),
color-stop(0.5, #66cc00));
}
This particular example uses lots of shorthand to make gradients simpler. For example,
the phrases
left top
and
left bottom
are shorthand for the endpoints of the gradient,
and
from
and
to
are shorthand for color stops that use those same endpoints.
4.7.2 CSS masks
A mask is a black-and-white shape that you use to show only part of an image. In a
mask, alpha values of 0 show nothing; alpha values of 1 display the image content. In
other words, it’s a way to clip an image.
WebKit masks can be used in a variety of ways. The properties:
can all be used to mask an underlying image in different ways.

-webkit-mask-image
should provide the simplest masking:
<img -webkit-mask-box-image
can provide some interesting border masking, if used
correctly:
<img src="yourpic.png" style="-webkit-mask-box-image: url(anothermask.png)

78 CHAPTER 4 Advanced WebKit and textual web apps
The downside will be that you can’t integrate Canvas into a web page in quite the
same way you can CSS. It’s a separate element, built around the
<canvas>
tag, rather
than a
CSS property, which means you’ll need to use some layered positioning or
something similar to work it into your web page. However, if you need the functional-
ity, then at least you have an alternative that will give you access to it.
4.8 Summary
The WebKit represents some of the quickest changing technology available for web
development on any platform. It’s the basis for the iPhone’s Safari, and that means
that you can expect web development on the iPhone to become an increasingly good
option as time goes on, further adjusting the balance of development choices that we
discussed in chapter 2. The fact that we couldn’t fully document some of its features
just emphasizes how quickly things are changing.
As an iPhone developer, you’ll probably be most excited by the iPhone-specific fea-
tures that have been implemented. The touch and orientation event handlers provide
Lessons for SDK developers
Engineers at Apple have been leading the charge in the design of the WebKit. It’s here
that we really start to see commonalities between WebKit and SDK development pat-
terns. Sometimes they’re close enough to help you bridge the gap between the two
styles of programming, and other times they’re far enough apart to cause confusion.
Database programming based on SQLite is the first feature that we’ll see repeated
in the SDK. Whereas the WebKit’s abstraction for the database is already advanced,
cleanly breaking out responses from input, the SDK still depends on SQLite’s native
API; as a result, if anything, database programming is easier in the WebKit than in
the SDK at the time of this writing. The SDK’s SQLite is covered in chapter 16.
The WebKit’s touch event handling is another element that we’ll see closely mirrored
in the SDK. Both use the same architecture of calling handlers when touches start,


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status