34,79 €
Undoubtedly, the iPhone is one of the most exciting mobile devices in the world. Its iOS is used in other Apple devices such as the iPad and iPod Touch. With this book you'll learn how to build and develop applications for these devices without applying Apple's burdensome and at times restrictive technologies. Just use your experience and knowledge combined with web front-end technologies like JavaScript to build quality web apps. Nobody will know you haven't used Objective-C and Cocoa.
The iPhone JavaScript Cookbook offers a set of practical and clear recipes with a step-by-step approach for building your own iPhone applications applying only web technologies such as JavaScript and AJAX. Web developers won't need to learn a new programming language for building iOS applications with a native look and feel.
The first part of the book introduces you to the world of iPhone applications. Understanding how it works is required for designing good user interfaces for this device. You will continue learning about how to apply multimedia features to your applications. Common features of web applications, such as AJAX and SQL, can also be applied to our iPhone applications. The third part of the book explains how to deal with specific features of iPhone such as the accelerometer. At the end, you learn how to offer additional features through external websites. With the iPhone JavaScript Cookbook, you will be able to develop outstanding web applications with a for Apple's mobile devices, offering your users all of the advantages of the native look and feel.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 341
Veröffentlichungsjahr: 2011
Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2011
Production Reference: 1170611
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849691-08-6
www.packtpub.com
Cover Image by Duraid Fatouhi (<[email protected]>)
Author
Arturo Fernandez Montoro
Reviewers
Taylor Jasko
Thomas Schreiber
Acquisition Editor
Steven Wilding
Development Editor
Alina Lewis
Technical Editors
Joyslita D’Souza
Merwine Machado
Aditi Suvarna
Copy Editors
Neha Shetty
Laxmi Subramanian
Project Coordinator
Zainab Bagasrawala
Indexer
Monica Ajmera Mehta
Proofreader
Lynda Sliwoski
Graphics
Geetanjali Sawant
Production Coordinator
Shantanu Zagade
Cover Work
Shantanu Zagade
Arturo Fernandez Montoro is a web software engineer, developer, author, and technical writer specializing in Free and Open Source Software.
His professional experience includes technologies, such as Django, Rails, J2EE, PHP, XHTML, CSS, and JavaScript, and working as a software developer and architect, project manager, sysadmin, and consultant for different companies in Europe.
Since 2002, he often writes for different Linux and Open Source printed and online magazines, such as Todo Linux, Linux+, Linux Magazine, Free Software Magazine, and Rails Magazine.
Currently, Arturo works as a Python/Django developer, contributing to one of the most important and visited websites in Spain. He can be reached at <[email protected]>.
Many thanks to my friends and colleagues Lui Palacios and Thomas Schreiber for contributing to this book with their advice and revisions.
My wife Alicia is a living proof of the power of love. Thank you for starting a family together.
This book would have never been possible without the help and work of the team at Packt Publishing. My sincere acknowledgements to Steven, Zainab, and Alina.
Special thanks to all people who contribute to Free and Open Source with their knowledge, effort, time, patience, and enthusiasm. We’re changing the world.
Thanks to my parents Jose and Aurora for teaching me to be the person I am today.
My brother Ernesto is someone who never gives up. Thank you for making my life enjoyable.
In memoriam of my grandmother Aurora, who passed away during the writing of this book.
Taylor Jasko, a student who is currently attending high school, has been fascinated with technology ever since the day he laid his hands on a Windows 95-based computer. Since then, now being eighteen years old, he has dived into web design and development, computer programming, and even system admin work with his favorite server-oriented operating system, Debian Linux.
He found the technology blog Tech Cores (http://techcores.com) and has been working on it ever since it was created back in late 2008. Tech Cores is a great example of his work; he designed and created it using the powerful WordPress content management system and with the help of his Wacom Intuos4 graphic tablet and Adobe Photoshop.
While in school, he can be found freelancing graphic designing and programming work. His technical strengths include PHP, JavaScript (including libraries like jQuery), AJAX, HTML, CSS, Perl, Objective C, Linux/UNIX, MySQL, Apache, Nginx, and to finish it all off, a dab of Python. Essentially, he’s a programmer, system admin, and a designer!
He can be reached at <[email protected]>.
Thomas Schreiber was born and raised in the United States and holds a Bachelor of Arts in Digital Media from Temple University’s Tyler School of Art. He is a Python web developer using Django, Pinax, and many other exciting technologies. He is also a techno musician who performed at and organized hundreds of events in Philadelphia spanning the last nine years. Thomas currently lives in Madrid with his wife Yulka, dog Finnegan, and is currently working as a lead web developer for Unidad Editorial on a social media platform. His detailed profile can be found at http://insatsu.us/collective/thomas-schreiber/.
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read, and search across Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Undoubtedly, iPhone is one of the most exciting mobile devices in the world. Its iOS is used in other Apple devices, such as iPad and iPod Touch. With this book, you'll learn how to build and develop applications for these devices without applying Apple's burdensome and, at times, restrictive technologies. Just use your experience and knowledge combined with web frontend technologies, such as JavaScript, to build quality web applications. Nobody will ever come to know that you haven't used Objective-C and Cocoa.
iPhone JavaScript Cookbook offers a set of practical and clear recipes with a step-by-step approach for building your own iPhone applications by only applying web technologies such as JavaScript and AJAX. Web developers won't need to learn a new programming language for building iOS applications with a native look and feel.
Chapter 1 , Frameworks Make Life Easier, is the "getting started" chapter of this book. It covers how to install and set up different frameworks, which will be used for the recipes of the book.
Chapter 2 , Building Interfaces, introduces you to the world of iPhone applications. You'll learn how to build essential and advanced interfaces, such as buttons, lists, forms, and date pickers.
Chapter 3 , Events and Actions, discovers how to deal with events and actions. Both allow us a better control of the interaction between the user and the device.
Chapter 4 , A Picture Speaks a Thousand Words, takes advantage of the great screens of iPhone and iPad teaching you how to display a grid of images, how to apply different effects, and how to work with the built-in camera of the device.
Chapter 5 , Mastering Sound and Music, explores the audio and video capabilities of iPhone. You'll learn how to play and record audio and how to create iPod playlists.
Chapter 6 , Exchanging Data: AJAX, covers how to use this technology for exchanging data between the server and the client. Readers are walked through the process of sending HTTP requests and processing JSON responses.
Chapter 7 , Working with Data: Storage and SQL, provides coverage of the process for storing and retrieving data using the SQL language. Also, you'll learn how to deal with different kinds of storage available in iPhone.
Chapter 8 , This is a Phone, enlightens that we cannot forget that iPhone is a smartphone. This is the reason to get focused on learning how to create, select and display contacts, and how to call a number and send an SMS.
Chapter 9 , Location, Location, Location, introduces to readers to geolocation, showing how to detect the current orientation and position, and how to use the API provided by Google Maps for displaying a map at a specific location.
Chapter 10 , Web 2.0 Integration, helps readers learn how to integrate their iPhone applications with third-party popular services such as Facebook, YouTube, Twitter, and Flickr.
If you're planning to build native applications, you'll need a computer with Mac OS X, iOS SDK, and Xcode installed.
Despite the fact that it's possible to use a WebKit-compatible web browser for the recipes of this book, we suggest to use a real Apple device, such as an iPhone and iPad. However, the iPhone Simulator is a very useful tool that you can use on your Mac for testing applications.
This book is for web developers interested in applying their knowledge for building web applications for iOS devices. You can develop your own iPhone web applications using nothing but JavaScript combined with XHTML and CSS. You can even give these applications a native look and feel though you wont be able to submit them to the application store. You will develop an application for iOS without having to learn the Objective-C programming language. This is the book for any iPhone developer looking to side step the totalitarian application store regime of Apple.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "we'll need to add a span element for the smallfield label."
A block of code is set as follows:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "After clicking on the Search button, we'll see our dialog box:"
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books — maybe a mistake in the text or the code — we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
In this chapter, we will cover:
Many web applications implement common features independent of the final purpose for which they have been designed. Functionalities and features such as authentication, forms validation, retrieving records from a database, caching, logging, and pagination are very common in modern web applications. As a developer, surely you have implemented one or more of these features in your applications more than once. Good developers and software engineers insist on concepts, such as modularity, reusability, and encapsulation; as a consequence you can find a lot of books, papers, and articles talking about how to design your software using these techniques. In fact, modern and popular methodologies, such as Extreme Programming, Scrum, and Test-driven Development are based on those principles. Although this approach sounds very appealing in theory, it might be complicated to carry it out in practice.
Developing any kind of software from scratch for running in any platform is undoubtedly a hard task. Complexity grows up when the target platform, operating system, or machine has its own specific rules and mechanisms. Some tools can make our job less complicated but only one kind of them is definitely a safe bet. It is here when we meet frameworks, a set of proven code that offers common functionality and standard structures for software development. This code makes our life much easier without reinventing the wheel and gives a skeleton to our applications, making sure that we're doing things correctly. In addition, frameworks avoid starting from scratch once more. From a technical point of view, most frameworks are a set of libraries implementing functions, classes, and methods.
Using frameworks, we can save time and money, writing less code due to its code skeleton, and features implemented on it. Usually, frameworks force us to follow standards and they offer well-proven code avoiding common mistakes for beginners. Tasks such as testing, maintenance, and deployment are easier to do using frameworks due to the tools and mechanisms included. On the other hand, the learning curve could be a big and difficult drawback for beginners.
Through this chapter, we'll learn how to install the main frameworks for JavaScript, HTML, and CSS development for iPhone. All of them offer a base to develop applications with a consistent and native look and feel using different methods. While some of them are focused on the user interface, others allow using AJAX in an efficient and easy way. Even some frameworks allow building native applications from the original code of the web application. We have the chance to choose which is better to fulfill our requirements; it is even possible to use more than one of these solutions for the same application. For our recipes, we'll use the following frameworks:
This recipe shows how to download and install the iUI framework on different operating systems. Particularly, we'll cover Microsoft Windows, Mac OS X, and GNU/Linux.
The first step is to install and get ready; some tools need to be downloaded and decompressed. As computer users, we know how to decompress files using software such as WinZip, Ark, or the built-in utility on Mac OS X. You will surely have installed a web browser on your computer. If you are a Linux or Mac developer, you already know how to use curl or wget. These tools are very useful for quick download and you only need to use the command line through applications such as GNOME Terminal, Konsole, iTerm, or Terminal. iUI is an open source project, so you can download the code for free.
The open source project releases some stable versions packed and ready to download, but it is also possible to download a development version. This one could be suitable if you prefer working with the latest changes made by the official developers contributing to the project. Due to this, developers are using Mercurial version control and thus we'll need to install a client for it to get access to this code.
iUI is an open source project so you can download the code for free. Open your favorite web browser and enter this URL:
http://code.google.com/p/iui/downloads/list
In that web page, you'll see a list with files that refer to different release versions of this framework. Clicking on the link corresponding to the latest release's drives takes you to a new web page that shows you a new link for the file. Click on it for instant downloading.
If you are a GNU/Linux user or a Mac developer you will be used to command line. Open your terminal application and launch this command from your desired directory:
Once you have downloaded the tarball file, it's time to extract its content to a specific folder on our computer. WinZip and WinRAR are the most popular tools to do this task on Windows. Linux distributions, by default, install similar tools such as File Roller and Ark. Double-clicking from the download window of the Safari browser will extract the files directly to your default folder on your Mac, which is usually called Downloads. For command-line enthusiasts, execute the following command:
After decompressing the downloaded file, you'll find a folder with different subfolders and files. The most important is a subfolder called iui that contains CSS, images, and JavaScript files for building our web applications for iPhone. We need to copy this subfolder to our working folder where other application files reside.
Sharing this framework across different web applications is possible; you only need to put the iUI at a place where these applications have permissions to access. Usually, this place is a folder under the DocumentRoot of your web server. If you're planning to write a high load application, it would be a good idea to use a cloud or CDN (Content Delivery Network) service such as Amazon Simple Storage Services (Amazon S3) for hosting and serving static HTML, CSS, JavaScript, and image files.
Installing the iUI framework is a straightforward process. You simply download and decompress one file, and then copy one folder into an other, which has permission to be accessed by the web server.
Apache is one of the most used and extended web servers in the world. Other popular options are Internet Information Server (IIS), lighttpd, and nginx. Apache web server is installed by default on Mac OS X; most of the operating systems based on Linux and UNIX offer binary packages for easy installation and you can find binary files for installing on Windows as well. IIS was designed for Windows operating systems, meanwhile, lighttpd and nginx are winning popularity and are used on UNIX systems as Linux's distros, FreeBSD, and OpenBSD. Ubuntu Linux uses /var/www/ directory as the main DocumentRoot for Apache. So, in order to share iUI framework across applications, you can copy the folder to the other folder by executing this command:
If you are a Mac user, your target directory will be /Library/WebServer/Documents/iui.
Inside the samples subfolder, you'll find some files showing capabilities of this framework, including HTML and PHP files. Some examples need a web server with PHP support but you can test others using Safari web browser or an other WebKit's browser such as Safari or Google Chrome. Open index.html with a web browser and use it as your starting point.
If you prefer to use the latest version in development from the version control, you'll need to install a Mercurial client. Most of the GNU/Linux distribution such as Fedora, Debian, and Ubuntu includes binary packages ready to install them. Usually, the name of the binary package is mercurial. The following command will install the client on Ubuntu Linux:
Mercurial is an open source project and offers a binary file ready to install for Mac OS X and Windows systems. If you're using one of these, go to the following page and download the specific file for your operating system and version:
http://mercurial.selenic.com/downloads/
After downloading, you can install the client using the regular process for your operating system. Mac users will find a ZIP file containing a binary package. For Windows, the distributed file is a MSI (Microsoft Installer), ready for self-installation after clicking on it.
Despite that the client of this version control was developed for the command line, we can find some GUI tools online such as TortoiseHG for Windows. These tools are intuitive and user-friendly, allowing an interactive use between the user and the source files hosted in the version control system. TortoiseHG can be downloaded from the same web page as the Mercurial client.
Finally, we'll download the version development of the iUI framework executing the following command:
The new iui folder includes all files of the iUI framework. We should copy this folder to our DocumentRoot.
If you want to know more about this framework, point your browser at the official wiki project:
http://code.google.com/p/iui/w/list
Also, taking a look at the complete code of the project may be interesting for advanced developers or just for people wanting to learn more about internal details:
http://code.google.com/p/iui/source/browse
UiUIKit is the short name of the Universal iPhone UI Kit framework. The development of this framework is carried out through an open source project hosted in Google Code and is distributed under the GNU Public License v3. Let's see how to install it on different operating systems.
As the main project file is distributed as a ZIP file, we'll need to use one tool for decompressing these kind of files. Most of the modern operating systems include tools for this process. As seen in the previous recipe, we can use wget or curl programs for downloading the files.
If you are planning to read the source code or you'd like to use the current development version of the framework, you'll need a Subversion client as the UiUIKit project is working with this open source version control.
Open your web browser and type the following URL:
http://code.google.com/p/iphone-universal/downloads/list
After downloading, click on the link for the latest version from the main list, for instance, the link called UiUIKit-2.1.zip. The next page will show you a different link for this file that represents the version 2.1 of the UiUIKit framework. Click on the link and the file will start downloading immediately.
Mac users will see how the Safari browser shows a window with the content of the compressed file, which is a folder called UiUIKit, which is stored in the default folder for downloads.
Command line's fans can use these simple commands from their favorite terminal tool:
After downloading, don't forget to decompress the file on your web-specific directory. The commands given next execute this action on Linux and Mac OS X systems:
The main folder of the UiUIKit framework contains two subfolders called images and stylesheets. The first one includes many images used to get a native look for web applications on the iPhone. The other one offers a CSS file called iphone.css. We only need the images subfolder with its graphic files and the CSS file.
In order to use this framework in our projects, we need to allow our HTML files access to the images and the CSS file of the framework. These files should be in a folder with permissions for the web server. For example, we'll have a directory structure for our new web application for iPhone as follows:
Remember that this framework doesn't include HTML files; we only need a bunch of the graphic files and one stylesheet file. The HTML files showed in the previous example will be our own files created for the web application.
We'll also find a lot of examples on different HTML files located in the root directory, outside the mentioned subfolders. These files are not required for development but they can be very useful to show how to use some features and functionalities.
For an initial contact with the capabilities of the framework it would be interesting to take a look at the examples included in the main directory of the framework. We can load the index.html in our browser. This file is an index to the different examples and offers a native interface for the iPhone. Safari could be used but is better to access from a real iPhone device.
Subversion is a well-proven version control used by many developers, companies, and, of course, open source projects. UiUIKit is an example of these projects using this popular version control. So, to access the latest version in development, we'll need a client to download it. Popular Linux distributions, including Ubuntu and Debian have binary packages ready to install. For instance, the following command is enough to install it on Ubuntu Linux:
The last versions of Mac OS X, including Leopard and Snow Leopard, includes a Subversion client ready to use. For Windows, you can download Slik SVN available for 32-bit and 64-bits platforms; installation programs can be downloaded from: http://www.sliksvn.com/en/download.
When you are sure that your client is running, you could execute it for getting the latest development version of the UiUIKit framework. Mac and Linux users will execute the following command:
All information related to the UiUIKit framework project could be found at: http://code.google.com/p/iphone-universal/
Frameworks and libraries such as jQuery, prototype, MooTools, YUI, and Dojo are becoming very popular among web developers. All of them present an easy way for using the DOM model of HTML in addition to the AJAX capabilities and other interesting features such as animations, including support for multiple browsers avoiding the complexity of cross-browser applications. It sounds pretty good but the problem is that they aren't focused on mobile devices. To solve this problem we're introducing XUI, a simple but powerful and lightweight JavaScript framework.
XUI is open source and can be downloaded from the main page of its website (http://xuijs.com/). As seen in the previous recipes, you will need a web browser or a command-line utility for downloading. Developers or people interested in development versions will need a client for it, the version control system used by the XUI open source project.
Open your web browser and type this URL: http://xuijs.com/downloads/.
In the list, we'll find different versions related to the general mobile devices and specific for BlackBerry and Windows Mobile operating systems. Each version has two different files, one minified and the other commented. The first one should be used for production environments. We'll download the commented version for general mobile devices, marked as webkit/firefox/opera. After clicking on the specified link, you'll have a new file called xui-2.0.0.js. If you prefer to use command line, you can execute the following command:
The last step will be to copy these files to a folder inside our DocumentRoot directory. For example, on Fedora Linux:
XUI is a pure JavaScript framework integrated only by files written in this programming language. In order to use this lightweight and fast framework, we only need to copy the two JavaScript files into a folder with permissions for our web server, and then include a reference on the HTML files of our web application for iPhone.
Inside the head section of our HTML files, we'll need to add this line:
A complete reference and documentation for the XUI framework can be found at: http://xuijs.com/docs.
All the source code for the XUI can be found at http://github.com/xui/xui.
The iWebKit is a framework focused on being fast, lightweight, and specifically for developing web applications and websites for Apple's devices. Installation is a straightforward process, as we'll see in this recipe.