Ricardo Alcocer is a Technical Evangelist at Appcelerator and works closely with the Titanium community. He’s been developing on Titanium since 2009 and recently relocated to California from his native Puerto Rico. Ricardo will be providing regular developer and beginner blog posts, so be on the lookout for more of his work and hit him up on Twitter (@ricardoalcocer) with any questions.
One of the most important features of mobile devices is their capability of connecting to the Internet. With an active Internet connection you can share posts on Facebook, update your Twitter status, and connect to your personal or enterprise Web Services.
Titanium comes out-of-the box with a very powerful HTTP Client module that resides under the Titanium.Network namespace. While browsing through Github repositories, I stumbled upon a very cool library called XHR, written by Raul Riera (@raulriera), a member of our Titanium User Community. This small library provides a wrapper around the HTTPClient that makes it very easy to use, plus adds some other nifty features.
So that’s the backstory. Let’s see an example.
Go ahead and download the library from https://github.com/raulriera/XHR. Make sure you download both xhr.js and ti.taffydb.js. I’m assuming they are both on the ‘lib’ folder.
Run this code, and you’ll see on your Titanium Studio Console, a JSON string holding 20 entries from the @appcelerator Twitter account, or an error if there was no Internet connection.
The HTTP responses are given to you nicely packaged in an object. In this example, this object is the variable ‘e’, and the actual data is under ‘e.data’. Naturally, you could also JSON parse the whole ‘e’ variable, and then look for your data under the ‘data’ branch of your response object.
HTTP Connections are the basis of today’s web and mobile applications. This library has become my default way of communicating with Web Services. Give it a try. You’ll love it.
In a future post, I’ll show you how to use this library consume data from JSON-based web services, and display them using native UI controls.
Great job Raul and Ben!