iPhone JavaScript: Web 2.0 Integration

Exclusive offer: get 50% off this eBook here
iPhone JavaScript Cookbook

iPhone JavaScript Cookbook — Save 50%

Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa

£16.99    £8.50
by Arturo Fernandez Montoro | October 2011 | Java

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. This article shows simple and effective ways to connect with the most important websites on the Internet. The techniques covered here shall provide a basis for building more complex applications. Our goal is to get a good understanding of each mechanism implemented in our recipes.

In this article by Arturo Fernandez Montoro, author of iPhone JavaScript Cookbook, we will cover:

  • Embedding an RSS feed
  • Opening a YouTube video
  • Posting on your Facebook wall
  • Retrieving recent tweets from Twitter
  • Displaying photos from Flickr

 

(For more resources on iPhone JavaScript, see here.)

Introduction

The mashup applications allow us to exchange data with other web applications or services. Web 2.0 applications provide this feature through different mechanisms.

Currently, some of the most popular websites like YouTube, Flickr, and Twitter provide a way for exchanging data through their API's. From the point of view of the user interfaces, mashups allow us to build rich interfaces for our application.

The first recipe for this article will cover embedding a standard RSS feed information. Later in our application we'll delve into YouTube, Facebook, Twitter, and Flickr and build some interesting mashup web applications for the iPhone.

Embedding an RSS feed

Our goal for this recipe will be to read an RSS feed and present the information provided n our application. In practice, we're going to use a feed offered by The New York Times newspaper, where each item provides a summary and a link to the original web page where the information resides. You could also choose another RSS feed for testing this recipe. The code for this recipe can be found at code/ch10/rss.html in the code bundle provided on the Packtpub site.

Getting ready

Make sure iWebKit is installed in your computer before continuing.

How to do it...

  1. As you've learned in the previous recipes, you need to create an XHTML file with the required headers for loading the files provided by iWebKit:

    <link href="../iwebkit/css/style.css" rel="stylesheet"
    media="screen" type="text/css" />
    <scriptsrc='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../iwebkit/javascript/functions.js"
    type="text/javascript"></script>

  2. The second step will be to build our simple user interface containing only a top bar and an unordered list with one item. The top bar is added with the following lines:

    <div id="topbar">
    <div id="title">RSS feed</div>
    </div>

  3. To add the unordered list , use the following code:

    <div id="content">
    <ul class="pageitem">
    <li class="textbox">
    <p>
    <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://rssxpress.ukoln.ac.uk/lite/
    viewer/?rss=http://www.nytimes.com/services/xml/
    rss/nyt/HomePage.xml" type="text/javascript"></script>
    </p>
    </li>
    </ul>
    </div>

  4. Finally, you should add the code for closing the body and html tags and save the new file as rss.html. After loading your new application, you will see a screen, as shown in the screenshot:

    iPhone JavaScript Cookbook

  5. If you click on one of the items, Safari Mobile will open the web page for the article, as shown in the following screenshot:

    iPhone JavaScript Cookbook

How it works...

For avoiding complexity and keeping our recipe as simple as possible, we used a free web service provided by RSSxpress. This service is called RSSxpressLite and it works by returning a chunk of JavaScript code. This code inserts an HTML table, containing a summary and a link for each item provided by the referenced RSS feed. Thanks to this web service, we don't need to parse the response of the original feed; RSSxpressLite does the job for us. If the mentioned web service returns the code that we need, you should only write a small line of JavaScript code referring to the web service through its URL and pass as a parameter the RSS feed for displaying information.

There's more...

For learning more about RSSxpressLite, take a look at http://rssxpress.ukoln.ac.uk/lite/include/.

Opening a YouTube video

It is safe to say that everyone who uses the Internet knows of YouTube. It is one of the most popular websites in the world. Millions of people use YouTube to watch videos through an assortment of devices, such as PC's, tablets, and smartphones. Apple's devices are not an exception and of course we can watch YouTube videos on the iPhone and iPad.

In this case, we're going to load a YouTube video when the user clicks on a specific button. The ink will open a new web page, which allows us to play it.

The simple XHTML recipe can be found at code/ch10/youtube.html in the code bundle provided on the Packtpub site.

Getting ready

This recipe only requires the UiUIKit framework f or building the user interface for this application. You can use your favorite YouTube video for this recipe. By default, we're using a video provided by Apple introducing the new iPad 2 device.

How to do it...

  1. Following the example from the previous recipe, create a new XHTML file called youtube.html and insert the standard headers for loading the UiUIKit framework. Then add the following CSS inside the <head> section to style the main button:

    <style type="text/css">
    #btn {
    margin-right: 12px;
    }
    </style>

  2. Our graphical user interface will be completed by adding the following XHTML code:

    <div id="header">
    <h1>YouTube video</h1>
    </div>
    <h1>Video</h1>
    <p id="btn">
    <a href="http://m.youtube.com/watch?v=Z_d6_gbb90I"
    class="button white">Watch</a>
    </p>

  3. After loading the new application on your device, you will see a screen similar to the following screenshot:

    iPhone JavaScript Cookbook

  4. When the user clicks on our main button, Safari Mobile will go to the web page of the video at YouTube, as shown in the following screenshot:

    iPhone JavaScript Cookbook

  5. After clicking on the play button, the video will start playing. We can rotate our device for a better aspect ratio, as shown in the following screenshot:

    iPhone JavaScript Cookbook

How it works...

This recipe is pretty simple; we only need to create a link to the desired YouTube video. The most important thing to keep in mind is that we'll use a mobile-specific domain for loading our video to mobile devices. The URL is simply http://m.youtube.com, instead of the regular URL http://www.youtube.com.

Posting on your Facebook wall

The application developed for this recipe shows how to authenticate with Facebook and how to write a post on your public wall. If everything is successful, an alert box is used to report it to the user.

Although there are myriad complex applications with better functionalities that can be built for Facebook, we will focus on simple posting in this recipe. This application will only allow you to post on your wall. For this you need to hardcode your Facebook account for posting. This is to keep the recipe as simple as possible and to get a good understanding of all the complex processes involved in dealing with the OAuth protocol used by Facebook. However, thanks to this open protocol, it is easier to allow secure authentication of APIs from web applications.

Also, this recipe requires using a real Internet domain and a server with public access. Thus, you cannot test this application on your local machine. Our application needs to use a server- side language for which we'll use PHP. Currently, it's very easy to find hosting services for PHP applications. You can also find very cheap services for hosting your PHP code.

You can find the complete code for this recipe at code/ch10/facebook/ in the code bundle provided on the Packtpub site.

Getting ready

To bu ild the application for this recipe, you need to have a public server with an Internet domain linked to it. Also, you must install a web server with a PHP interpreter and have the UiUIKit framework ready to use. You need to install the cURL library, which allows PHP to connect and communicate to many different types of servers. Two interesting resources for this issue are:

 

iPhone JavaScript Cookbook Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa
Published: June 2011
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

 

(For more resources on iPhone JavaScript, see here.)

How to do it...

  1. The first step required for this recipe is to make sure that you have a public server with PHP and a web server installed and running. As a web developer, you may already have one. At least, you're capable of configuring this server-side environment quickly and without too much effort. We're going to assume that your server environment is ready before continuing.
  2. The next step is easier than the first one. Just check if your UiUIKit framework is installed in your server.
  3. As we're going to use the Facebook Graph API, we'll need to find out the specific Facebook ID (identifier) for our user. In order to do that, we go to Facebook's home page. After authenticating, you can click on the Profile link and a new URL will appear on your browser's navigation bar. This URL ends with a string after a slash character. Actually, the mentioned URL has this structure: http://www.facebook.com/home.php#!/<profile_name>, where <profile_name> is your Facebook ID. Now your ID is strictly a number, but we'll use the string mentioned earlier, which works as an alias to the ID.
  4. Another important and required step will be to register our application with Facebook and fortunately, this process is straigtforward. Since Facebook needs to verify that you're the owner of the profile and can create applications, you'll be asked to provide your mobile phone or credit card information. It's simpler and faster to use your mobile phone. After typing your number, you'll receive an SMS with a code. Then, type this code in the required field of the form. The process starts by accessing http://developers.facebook.com. Then, click on the My apps link. When the new web page is loaded, push the + Set Up New App. You can find a form, fill it and click on the Create Application button. Now, you've got your application registered and have received a unique set of values like Application ID, API Key, and App Secret. We'll use some of these values later.

    iPhone JavaScript Cookbook

  5. After clicking on the Create one link, you' ll see a form as shown in the next screenshot:

    iPhone JavaScript Cookbook

  6. Now it's time to build our main page for allowing the user to write a post. For taking this action, we're going to create a new XHTML page (iposting.html) inside a new folder called facebook under the control of your web server. We'll use the standard XHTML headers plus the required lines for loading the UiUIKit framework. Then, we'll add the following lines of code for building the user interface:

    <div id="header">
    <h1>iPosting</h1>
    </div>
    <form name="frm" method="post" action="posting.php">
    <ul class="form">
    <li>
    <textarea name="ptext" rows="4"
    placeholder="Type here"></textarea>
    </li>
    </ul>
    <p>
    <a href="javascript: document.frm.submit()"
    class="button white">Post to your wall</a>
    </p>
    </form>

    iPhone JavaScript Cookbook

  7. When this file is ready, we need to create our PHP page for cal ling Facebook and posting on our wall. Our PHP is named posting.php and we'll start by adding the following lines:

    session_start();
    $ptext = '';
    if (empty($_REQUEST['ptext'])) {
    $ptext = $_SESSION['ptext'];
    } else {
    $ptext = $_REQUEST['ptext'];
    $_SESSION['ptext'] = $ptext;
    }

  8. Then, we need to hardcode some values:

    $app_id = your_app_id;
    $app_secret = "your app secret here";
    $my_url = "your redirect page";
    $scope = "offline_access,publish_stream";
    $url_fb = "https://graph.facebook.com/<ID>/feed";

    Don't forget to change the values for the $app_secret and $url_fb variables. You must use your own values.

  9. The following lines handle communication and authentication with Facebook:

    $code = $_REQUEST["code"]
    if(empty($code)) {
    $dialog_url =
    "http://www.facebook.com/dialog/oauth?client_id="
    $app_id . "&redirect_uri=" . urlencode($my_url) .
    "&scope=". $scope;
    echo("<script>top.location.href='" . $dialog_url . "'
    </script>");
    }
    $token_url =
    "https://graph.facebook.com/oauth/access_token?client_id="
    $app_id . "&redirect_uri=" . urlencode($my_url) .
    "&client_secret=". $app_secret . "&code=" . $code;
    $access_token = file_get_contents($token_url);
    $arr_token = split("access_token=", $access_token);
    $acc_token = $arr_token[1];
    $graph_url = "https://graph.facebook.com/me?" . $access_token;
    $user = json_decode(file_get_contents($graph_url));

  10. Once we have permission for posting, we need to get a POST request using cURL:

    $fields = array(
    'access_token'=>urlencode($acc_token),
    'message'=>urlencode($ptext)
    );
    $fields_string = '';
    foreach($fields as $key=>$value) { $fields_string .=
    $key.'='.$value.'&'; }
    rtrim($fields_string,'&');
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url_fb);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_exec($ch);
    curl_close($ch);

  11. Finally, we close our PHP script adding the same XHTML code used in iposting. html. After taking this action, we'll add the following JavaScript code before closing the < body > tag:

    <script type='text/javascript'>
    alert('Text was published in your wall');
    </script>

    iPhone JavaScript Cookbook

  12. The result of posting on your wall is shown in the following screenshot:

    iPhone JavaScript Cookbook

  13. Now we have finished coding. To test that everything works, you'll need to upload the application to your server. Then, you can load the following URL in your device: http://yourdomain/iposting.html.

How it works...

Once we ha ve our new application registered with Facebook, we can start developing it. The first page (posting.html) works as the starting point and it offers a textarea widget for writing the post, which will be sent to our wall. After clicking on the main button, a standard HTTP POST request is sent to our iposting.php page. This PHP script checks and stores the content of our widget in a session variable. We need to do this action because iposting. php will call the Facebook API in order to authenticate our application. Without storing this value in the session, it will be lost and will not be authenticated. Actually, our PHP script first calls a web page specifically designed by Facebook for using the OAuth protocol. If the u ser is not logged in our application will redirect to a Facebook login page. Once the user has been authenticated by entering the e-mail and password, the control will be returned to our posting.php. This is the reason for using the following code line:

$my_url = "http://yourdomain/posting.php";

After our PHP recovers the control, it will do a HTTP POST request using cURL. This request will write our post on the wall.

The values offline_access and publish_stream are used by the variable $scope for indicating which kind of permissions we require for our application. Actually, these two values are required for posting from our iPhone application. Thanks to these parameters, Facebook knows which questions will be asked to the user for exchanging data with our application. This means that the user always knows what kind of actions could be taken for the application.

We just copy the XHTML code inside our PHP scripts to make it easier. The complex code could be confusing so it is better to copy this code for understanding how it works. Obviously, you should refactor this code for better performance.

For a real production application, we recommend to check for errors before making the HTTP POST to Facebook. Remember, some changes will be required to get this application production ready. Don't forget our goal was to keep it simple.

There's more...

It could be very interesting to take a look at the Facebook Graph API documentation at http://developers.facebook.com/docs/reference/api/, where you can find a lot of information for building more complex web applications for Facebook interaction.

More information about how the Facebook's authentication process works can be located at http://developers.facebook.com/docs/authentication.

If you're interested in finding out which is the OAuth protocol and how it works, you can visit its official website at http://oauth.net/.

Retrieving recent tweets from Twitter

Undoubtedly, Twitter is one of the most popular Web 2.0 applications on the Net. Many developers have found ways to connect this service to their iPhone applications .This recipe shows you how to load n tweets from a specific Twitter user. All of these tweets will be displayed in a simple list.

The required code for this recipe is a simple XHTML file called code/ch10/twitter.html in the code bundle provided on the Packtpub site.

Getting ready

First you need a Twitter account name; you may already have one. Then, make sure you've installed XUI and UiUIKit frameworks on your machine.

How to do it...

  1. After creating a standard XHTML file with the required lines for loading both our frameworks, add the following lines to set up the user interface:

    <body id="normal">
    <div id="header">
    <h1>Last tweets</h1>
    </div>
    <ul id="tlist"></ul>

  2. Then, we're going to add some JavaScript code for retri eving our last tweets:

    <script>
    functionmy_tweets(tweets) {
    varele = "";
    for (i=0; i<tweets.length; i++) {
    ele += "<li>" + tweets[i].text + "</li>";
    }
    x$('#tlist').html(ele);
    }
    </script>
    <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://twitter.com/statuses/user_timeline/
    bsnux.json?callback=my_tweets&count=5"></script>

  3. Finally, close and save your new file. After loading it on your device, you will see the result as is shown in the following screenshot:

    iPhone JavaScript Cookbook

How it works...

The UiUIKit framework is used in this recipe for building our simple user interface. On the other hand, XUI helps us to process the result response sent by Twitter. In order to do that, we only need to use a JavaScript line for making a JSON request through AJAX. Actually, our recipe is using the Twitter username bsnux and we're loading the latest five tweets posted by this user. For using your own user, just replace the mentioned username with a user of your choice. Also, you can change the number of the requested tweets by changing the value of the count variable.

The JavaScript my_tweets() function works as a callback, receiving the tweets and processing the response for creating our simple list.

There's more...

We can modify our original recipe for displaying the profile picture of the owner of each tweet. The change is pretty simple, just replace the JavaScript line:

ele += "<li>" + tweets[i].text + "</li>";

With the following line:

ele += "<li><img class='ico' src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original='" +
tweets[i].user.profile_image_url + "' />" + tweets[i].text +
"</li>";

The result of loading this new application is shown in the next screenshot:

iPhone JavaScript Cookbook

Displaying photos from Flickr

The last recipe of this article covers the Flickr service. This website is one of the most popular services for uploading and sharing photos online. We'll build an application for loading the last 20 photos published by a user. Later, the photos will be displayed using a grid widget.

Getting ready

Also with the previous recipes in this article, we're going to use the XUI and UIUiKit rameworks. Make sure both of them are installed and ready to use on your machine.

How to do it...

  1. After creating your new flickr.html file with the standard XHTML headers and the required lines for loading both our frameworks, we'll be ready to add the code for this recipe.
  2. First we'll set CSS styles for a consistent background color for our application:

    <style type="text/css">
    body {
    background: rgb(197,204,211) url(../images/stripes.png)
    !important;
    }
    </style>

  3. Then we'll add JavaScript code so we can connect to the Flickr API and get our photos:

    function buildPhotoURL(photo, psize) {
    psize = (typeof(psize) == 'undefined') ? '_s' : psize;
    var url = "http://farm" + photo.farm + ".static.flickr.com/" +
    photo.server +"/" + photo.id + "_" + photo.secret + psize +
    ".jpg";
    return url;
    }
    function get_data() {
    x$(window).xhr('http://api.flickr.com/services/rest/?
    method=flickr.people.getPublicPhotos&per_page=20&page=1
    &user_id=41152606@N03&jsoncallback=?
    &api_key=1a66f4e75c44f13656d97a712a443740&format=json',
    {
    callback: function() {
    var jsonData =
    this.responseText.substring(14,
    (this.responseText.length-1));
    var data = eval("(" + jsonData + ')');
    var ele = "";
    for (var i=0; i < data.photos.photo.length; i++) {
    var photoURL =
    buildPhotoURL(data.photos.photo[i]);
    ele += "<li><imgsrc='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original=" + photoURL + " />";
    }
    x$('#grid').html(ele);
    }
    });
    }

  4. Finally, we're going to add the html elements for building our user interface with the grid widget:

    <body id="images" onload="javascript: get_data()">
    <div id="header">
    <h1>Flickr Album</h1>
    </div>
    <ul id="grid">
    </ul>
    </body>

  5. The final result is shown in the next screenshot:

    iPhone JavaScript Cookbook

How it works...

The Flickr API provides a method for retrieving the latest tweets for a specific user. We only need to call to make a JSON request. Our application is using the on_load handler for retrieving the pictures directly after the application loads.

Using XUI, we're adding a new < li > element to our main < ul> tag to represent our grid widget. The response sent by Flickr is a JSON object containing different information about our photos. This object is an array where each element offers us information about each photo.

Additionally, our buildPhotoURL() JavaScript function i s used for building an absolute URL to each one of the photos. Thanks to this technique, when the user clicks on one picture, Safari Mobile will load the original photo from Flickr.

Summary

In this article we covered how to integrate your iPhone applications with third-party popular services such as Facebook, YouTube, Twitter, and Flickr.


Further resources on this subject:


iPhone JavaScript Cookbook Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa
Published: June 2011
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

About the Author :


Arturo Fernandez Montoro

Arturo Fernandez Montoro is a software architect specializing in design, development, testing, and deployment of high-traffic web applications.

Since 2002, he often writes for different Linux and Open Source printed and online magazines, such as Todo Linux, Linux+, Linux Magazine, and Free Software Magazine. Also, he has written the iPhone JavaScript Cookbook for Packt Publishing.

His professional experience includes technologies such as Django, Ruby on Rails, J2EE, PHP, web application servers, relational and NoSQL databases, JavaScript, HTML5, and CSS. He spent the last three years working as a software architect and a Python/Django lead developer.

Currently, Arturo lives in Madrid working as a software architect for QDQ Media, the biggest online marketing agency in Spain. He can be reached at arturo@bsnux.com.

Books From Packt


Xcode 4 iOS Development Beginner's Guide
Xcode 4 iOS Development Beginner's Guide

Unity iOS Game Development Beginners Guide
Unity iOS Game Development Beginners Guide

Core Data iOS Essentials
Core Data iOS Essentials

Cocos2d for iPhone 0.99 Beginner's Guide
Cocos2d for iPhone 0.99 Beginner's Guide

iPhone JavaScript Cookbook
iPhone JavaScript Cookbook

Unity iOS Essentials
Unity iOS Essentials

Learning jQuery, Third Edition
Learning jQuery, Third Edition

jQuery UI Themes Beginner's Guide
jQuery UI Themes Beginner's Guide


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software