day3

Seven days with Titanium – day 3 – ajax(xhr) and webviews

In “day 3” we will learn how to make our application communicate with a webserver. There are 2 ways we can do this: one is to use a webview and point it to a real web page or using the HttpClient that Appcelerator provides us.

The WebView

What is WebView? A WebView is nothing more than a chromeless browser or, if you want, a “naked” browser (it misses the interface we’re used to) that allows us to open remote or local webpages and display it in our apps.

You can use the webview for many purposes starting from displaying some nice html/css formatted text to building your own in-app browser. One thing you must NOT forget is that the webview it’s very expensive for the device (in terms of CPU load and memory usage) so try to use it only when it’s really really needed.

The webview is created using the function Titanium.UI.createWebView. Some things to specify about it would be that you have to choose between managing the touch events as a Titanium entity, or let the webpage do this. You cannot have both in the same time.

Two events that deserve more attention are beforeLoad and load that can be used to show and hide a “loading…” screen from the moment you try to load a remote page until the webpage is fully loaded.

The HttpClient

If you need to communicate with a server on a lower level (REST APIs, your own server implementation, etc) you can use the HttpClient that is equivalent of XHR (or ajax) in web.

When you use HttpClient you need to take in account two things:

  1. that the call is made asynchronous so your app logic needs to work this way
  2. that you need to make it in a certain sequence: create, set events, open, send.

So you need to create the HttpClient, set its onload and onerror events (that triggers when the call reply is received or an error occurs), open the channel and send the request – with or without parameters.

var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function()
{
	Titanium.API.info('loaded');
 
};
xhr.onerror = function()
{
	Titanium.API.info('error');
};
xhr.open("GET","http://google.com");
xhr.send();

Within the function used with onload event you can use the responseText (normal or json reply), responseXML(XML reply) or responseData (binary reply) for further proccessing.

Things to mention when you use networking with your apps

Always let the user know that something is processing in the background – on a slow internet connection the users will believe the app crashed and will probably kill it.

For iPhone: if there is no network you need to alert the user about it – this is an Apple request and failing to do so might lead them to reject your app. This can be verified with the boolean Titanium.Network.online.

JSON , XML

When it’s about sending structured data over httpthe server can reply in a JSON or XML format. I prefer JSON for two reasons:

  1. The JSON format is Javascript native
  2. the overall size of the information received from the server is smaller, so the reply comes faster.

Titanium can use both formats: JSON with JSON.parse(string) and JSON.stringify(object) to manipulate the data and XML with the Titanium.XML. The XML string needs to be parsed and the result, an DOM2 object, needs further processing with the DOM2 own methods.

So as you see XML can get ugly( or at least for me). Because of this I use when possible YQL.

YQL

YQL is the SQL for the web (a SQL like implementation for HTML build by the guys from Yahoo) that allows you to use a syntax similar to SQL for the DOM elements in a webpage. I won’t go further into details, you can do it by yourself on the YQL page.

What I will show you is how to convert an XML reply into JSON using the Titanium.Yahoo.yql module.

First of all you need to go to the YQL Console page and try to transform an rss feed – that is pure XML into JSON. Go to this link, select JSON as format, empty the callback function input, un-check the Diagnostics checkbox and run the test. You will get the XML file converted in JSON.

We can do the same using the YQL module that Titanium provides us:

 
Titanium.Yahoo.yql(
   'select * from xml where url="http://developer.appcelerator.com/feed/questions/created"',
   function(e) {
    // e.data holds the reply in json format
   }
);

We covered a little the basic networking in Titanium but there are unlimited ways on how you can use it.

More resources

As always KitchenSink scroll at the end and take a look at all xhr*,xml*, yql* files.

A full Twitter APIs/Titanium XHR tutorial – a must read.

And of course the official documentation:

If you have any questions or suggestions don’t hesitate to post them here.

Check the Spanish version of this post:
Siete días con Titanium – día 3 – ajax(xhr) y webviews

14 thoughts on “Seven days with Titanium – day 3 – ajax(xhr) and webviews”

  1. Dan, could you please give more explanation how JSON parse working? Tried to find samples in KitchenSink (Tweeter) but they’re using eval function for parsing. Not so many info in Titanium API docs.

    Thanks.

    Dmitry

  2. JSON.parse just converts a valid Json string in an object ( just like eval does ) only that this is done using the built in objectiveC class and not javascript, so for larger strings will be faster.
    You simply do something like this:

    var my_str = '{name:"Dmitry",email:"your_email"}';
    var my_obj = JSON.parse(my_str);

    and you will be able to access the object’s my_obj:
    my_obj.name ( this will be Dmitry ), my_obj.email ( = your_email)

  3. Hi Dan

    I am creating a chat application using appcelerator . i dont know how to authenticate with chat server could you please help me on this matter

  4. Is it possible to load an external web page through the webview? I don’t want to load Safari, but rather display the page in the app.

Comments are closed.