Category Archives: iPhone

Create applications for iPhone and iPad using Phonegap, Titanium Appcelerator and other frameworks. News, opinions and interesting apps.

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()
xhr.onerror = function()

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


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 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:

   'select * from xml where url=""',
   function(e) {
    // 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

Seven days with Titanium – day 2 – tables and pickers

Welcome to day 2 with Titanium – Tables and pickers. A short reminder of what we’ve done till now:

Believe it or not, the table is the most used UI element in the iPhone SDK. If you play a little with the applications that come with your “iDevice” you will see that almost all the native apps have tables. Sometimes they are so well designed and the appearance so changed that you don’t even think of them as tables. But in time, while you will learn more, you will be able to spot it and a lot of ideas will come to you :). Also I think that that the pickers are some sort of “undercover tables” so that’s why I’ll present both in the same tutorial.

The Table element

The table element is created using Titanium.UI.createTableView function. This function accepts an object as argument like we are used to – with the different settings we might want to give to the table. Besides the usual properties ( like top, left, etc) we have a very important one named data.

The Data property

The data property will hold the rows of the table as an array. The below code will show you what I’m talking about:

var win1 = Titanium.UI.createWindow({
var table1 =  Titanium.UI.createTableView({
		{title:"Row 1 - simple row"},
		{title:"Row 2 -  with child", hasChild:true},
		{title:"Row 3 -  with detail", hasDetail:true},
		{title:"Row 4 -  with check", hasCheck:true},
		{title:"Row 5 -  red background", backgroundColor:"#f00"}

So, what are we doing here?

We create a window. As we said in day 1, the application needs to have at least one window. Into this window we add table1 with the rows set as above.

This is the simplest way to do it, with the properties of the rows set as the Titanium.UI.TableViewRows documentation page specifies.

If you develop cross-platform you’ll need to take in account that each platform will show the data in it’s way (and some specific things may be missing). Below are 2 screenshots on how the above code looks on iPhone and Android.

Simple table with Titanium on iPhoneSimple table with Titanium on Android

A very important thing to know about tables

The rows into tables are rendered “on request”, so let’s say you have 20 rows – it’s clear that visible will be only a few (10 on a standard height). To save memory and to speed up the application the other rows will be rendered when the user scrolls the table. To do this faster the OS of the device creates some sort of template for each layout of the rows and reuse it changing only what’s different. To take advantage of this you MUST set a className attribute for the rows that share the same layout ( I didn’t do it above to simplify the code).

It is important mainly because for a few rows the memory usage is not too high, but for many rows – depending on how many and what’s inside the row – the app will move slow or even crash. The className can be any string you like:

{title:"Row 1 - simple row", className:"layout_one"}

More about tables

Each table has at least one section and each table can be plain (as above) or grouped. Let’s create a grouped table:

var table1 =  Titanium.UI.createTableView({
var section1 = Titanium.UI.createTableViewSection();
section1.headerTitle = "Hello";
var row1 = Titanium.UI.createTableViewRow({title:"Hello 1"});
var row2 = Titanium.UI.createTableViewRow({title:"Hello 2"});
var section2 = Titanium.UI.createTableViewSection();
section2.headerTitle = "Hello2";
var row3 = Titanium.UI.createTableViewRow({title:"Hello 3"});
var row4 = Titanium.UI.createTableViewRow({title:"Hello 4"});

And the result

Grouped table with Titanium on IphoneGrouped table with Titanium on Android

As you see I used the method setData() to set the content of the table after it is created.

This method accepts any array of sections created with Titanium.UI.createTableViewSection , rows created with Titanium.UI.createTableViewRow or objects that describe the rows as in the first example.

Custom tables

All the above examples show you how to create simple tables. If you want to create a more complicated layout you will need to create custom rows for this and The Custom Rows tutorial explains how to do it..

The Pickers or PickerViews

The pickers are the equivalent of the select tag in html. The only difference is that you can create a multicolumn picker (which in HTML it’s not possible without using some tricks). The function that creates a picker is Titanium.UI.createPicker

A simple picker it’s created with the following code:

var picker = Titanium.UI.createPicker();
var data = [];

Sadly for now it is implemented only on the Apple platform (please correct me if I’m wrong) so here it is how it should look like:
Picker with Titanium

The type property of the picker lets you chose form the next predefined types but you always can create your own multicolumn picker.

Titanium.UI.PICKER_TYPE_PLAIN (default),

var picker = Titanium.UI.createPicker({

Date and time picker

Since the tables and the rows are similar you will be able to create your custom rows in the same way as for the tables using of course the specific functions for the picker (linked at the end of the tutorial).

I won’t go further as the post is big enough already but I’ll try in the future to create a set of posts that will be specific to an UI element and where I’ll try to “dissect” it as much as possible.

More resources

Here are some links to follow for more information:

As always, thank you for reading this and I’m waiting for your questions and suggestions. If you have your own tutorials or links I’ll be glad to add them here to improve the quality of the posts.

See you on day 3.

Check the Spanish version of this post:
Siete días con Titanium – día 2 – tablas y selectores

Seven days with Titanium – day 1 – windows, views, navigation and tabs

Today is going to be the first day of the Titanium tutorial for beginners and a pretty long post.
Before we begin here is the recap of what we have written until now (and updated what will come): Seven days with Titanium – day 0 – introduction

As specified in the Introduction post I will try in this lesson to say some things about navigation, windows, views and tabs – the basics of the interface.

I will try to first to enumerate each of these elements and then explain what they do and how to use them. Also each interface element has a link to it’s documentation page on Appcelerator site.

Everything that is related to the interface you will find it into the Titanium.UI module. There are also some platform specific modules that cover elements of interface present only on the specific platform: Titanium.UI.Android,Titanium.UI.iPhone,Titanium.UI.iPad but for now we won’t talk about them.

The Window element

The basic element in a Titanium application is a Window. There is nothing complicated here, it’s a “container” for all the other elements if you wish. An application can have one or more windows but it must to have at least one window. A Window it’s one of the few elements that can exist by itself without the need to be a child of something.

The View element

Another basic element it’s a View. The View can be the analog of a div tag in HTML so basically it’s just a rectangle that can hold other elements for an easy and convenient control of the application’s layout. A View cannot exists by itself it will have to be a child of a Window or other element that accepts Views as child (a TableRowView or another View for example).

The TabGroup and the Tabs

The main navigational elements (and common to all platforms) is the TabGroup and the Tabs. Exactly what the names says – analog with a browser with tabs capabilities , a TabGroup will hold more Tabs. Each Tab will control (open) a window. If you decide that you application will have a TabGroup this will be the “root” of the application. What does it mean? That any window opened by the Tabs in TabGroup will be controlled by this and the TabGroup has one instance only and it cannot be closed or removed, but only hidden.

There is also an iPhone specific navigation element, named NavigationGroup that allows to navigate through windows without the need to create the navigation toolbar/buttons by ourselves.


This is how an application with a TabGroup, 2 Windows, 2 Tabs and a View looks loke on the Android and the iPhone platforms.

Seven days with Titanium- day 1 - androidSeven days with Titanium- day 1 - iPhone

More details about each element

Before we continue it would be great to take a look at each element documentation page because there is a lot of valuable info there. As you see, each interface element has some properties that are setters and/or getters like top, backgroundColor, etc), some methods (add(), open()) and events – usually user interaction events (touchstart, doubletap, etc) or specific events (open,close). Very similar with the web elements.

I want to specify some things:
sizes are in pixels but without the usual “px” notation, or in percents – but this requires to be written as a string:


colors are in hexa rgb , the short or the long form , don’t use names:


Let’s try to elaborate a little.

The Window element, again

The window element is created using the function Titanium.UI.createWindow.

var win1 = Titanium.UI.createWindow({  
    title:'Tab 1',

What the above code means? That we pass to the createWindow function an object argument with all the properties that we want to set.

This could be written like this:

var win1 = Titanium.UI.createWindow();
win1.title='Tab 1'

I think it’s pretty clear so I won’t go further with the code for view, tabs and so on. It’s similar to this only that you use Titanium.UI.createView, etc

How the tabGroup, tabs and the windows are related

The logic behind the above UI elements it’s as it follows:

The tabGroup is the root of the application, the “master”, it cannot be included in any other UI element.
This holds the tabs( at least one) and a tab, when clicked, opens the window associated with it.

Here is a sample code:

// create tab group
var tabGroup = Titanium.UI.createTabGroup();
// create base UI tabs and  windows
var win1 = Titanium.UI.createWindow({  
    title:'Tab 1',
var tab1 = Titanium.UI.createTab({  
    title:'Tab 1',
var win2 = Titanium.UI.createWindow({  
    title:'Tab 2',
var tab2 = Titanium.UI.createTab({  
    title:'Tab 2',
//  add tab
// open tab group;

The above code will generate a similar interface with the screenshots without the labels “I am window 1” etc and the red view. This would be a good exercise for you :).

Important !

As you see we set the same titles to tab1 – win1 and to tab2 – win2. This is not mandatory from the code point of view. The window associated to each tab is specified using the window property that points to the previous declared window. Why it’s like this then? It’s about usability. The user needs to have the same values when he/she has to associate two visual elements or will get confused. Also Apple might not like this when you will submit your app.


The above code it’s found in the default app.js file that you get when you create a new project. I only explained a little how things are.

A very very good resource it’s the KitcheSink project form Appcelerator team, found here.

For the advanced coders this is another tutorial on how to create a tooltip with Titanium that basically it’s just a view with a background image.

I think it’s enough for day 1, the post is too long and I’ll only add that I’m waiting for your questions, suggestions and critics if I made any mistake 🙂 With your questions/suggestions I’ll update the post or create a new one linked to “day 1”.

Check the Spanish version of this post:
Siete días con Titanium – Día 1 – Ventanas, vistas, navegación y pestañas

Seven days with Titanium – day 0 – introduction

What is all about?

I intend this to be a set of seven tutorials to help beginners understand how to work with the Titanium mobile framework.

The guys at Appcelerator did a great job with the framework allowing to us, the web developers, to have access on native applications for mobile devices ( Apple iDevices, Android and soon BlackBerry).

The framework reached the 1.4 version and each day more developers seem to be interested in using it – especially because it’s free. The community is great and you’ll find answers on almost any problem you might have. But for the beginners is still a little difficult to start. From here surged the idea of this set of tutorials in which I will try to cover the basics of the development process for iPhone and Android.
Titanium Appcelerator

Some things to start

Each post will contain a header with the previous tutorials written, for an easy follow. It will also have a footer part where some links of interest will be published.

It won’t be daily posts, I will write when I’ll have enough time to test and write the examples. I prefer a better written post to a fast one. And each post might be updated to add forgotten things (or to fix issues) so don’t forget to bookmark it.

The provided code will be licensed under the MIT license so you will be able to use it as you wish.

What should I know and/or what do I need?

Basically you need only Javascript knowledge. Some OOP coding routine would be great but is not mandatory ( we learn on the fly 🙂 .

    To develop for Android you will need Android SDK( Linux / OsX / Windows )
  • To develop for iPhone you will need a Mac ( Apple’s rules not mine)

I will not show you how to install any of the frameworks, SDKs, etc. There are good tutorials and HowTo’s that will show you this so I don’t want to repeat what’s already out there.

What do I need to forget?

May look strange but you really have to forget about something: DOM. Why? Because there is no DOM in there. We are not anymore in the HTML world. So nothing from HTML applies here. There are similar things (events for example) but everything it’s just an analogy to make it easier to use it.

Forget also about using a library ( yes, no MooTools, jQuery, etc…), or at least for a start. Again why? Because all these libraries are DOM oriented and are used to fight with multiple browsers, to please each of them and this adds bloatware to your code – code that will not be used by the devices anyway.

Why “at least for a start” ? Well, later you might miss some functions and methods these libraries have (let’s say the array methods like filter, each, unique, etc… ) but you will be able to implement this by your own and avoid a 150k library.

What you will NOT learn in these tutorials:

You won’t learn Javascript (you need to know it already). You will not learn ObjC and/or Java (in the end this is the purpose of Titanium). I will try to provide the code for each thing you will learn about as well as screenshots and maybe videos.

And at last

What will you learn:

Day 1:

Some things about navigation, windows, views and tabs – the basics of the interface. I will try to briefly explain what does each of these elements and how to use them.

Day 2:

Tables and pickers (or option pickers, the ‘select’ tag equivalent)

Day 3:

Ajax (actually XHR) – on how to use the HttpClient for webpages, XML, JSON and YQL; The webview – how to embed html code in your apps.

Day 4:

Media – images, movies and sounds

Day 5:

GPS and maps.

Day 6:

Some eye-candy with animations and transforms

Day 7:

About orientation and accelerometer.

Day 8:

This will be a post-tutorials day where I’ll sum up the lessons, add links and so on.

I know I said seven days and in the end are 9, but this one and the last do not count as “learning” days. There is a lot of stuff left out like scrollviews, sliders, some modules – Facebook? – more advanced techniques – like app events – but hopefully these will be the subject of another tutorials.

Let me know your thoughts, if you have ideas of what should I write about – remember that this is a beginner’s guide – or to ask questions.

See you in day 1.


PDF documents on how to install Titanium on each of the supported platforms ( Linux / OsX / Windows ) can be found on Titanium Appcelerator blog, go get them 🙂

Check the Spanish version of this post:
Siete días con Titanium – Día 0 – Introducción

Making a combo-box in Titanium Appcelerator – code and video

Sometimes we need a true combobox for our projects but iPhone SDK does not have a native one (at least from what I know) and of course neither has Titanium.

So we will build one. A “true” iPhone or Ipad combobox that allows you to use the same textfield to input arbitrary text or select a value from a UIPicker element.

Updated with @CJ_Reed’s screenshot and code at the final of the tutorial.

Let’s see the video first, then we’ll get to work:

Ok, what do we need for this iPhone combobox ?

First of all we need a textField to accept input from the user. Titanium lets you set the leftButton and rightButton for this textField while constructing it. So we will take advantage of this and create a textField as it follows:

var my_combo = Titanium.UI.createTextField({
	hintText:"write your name or select one",

Nothing special, a regular textField with a hint for the user that will disappear when the textField has a value.

Now we need to create the rightButton for it.

We will use a system button provided by Apple (Titanium.UI.iPhone.SystemButton.DISCLOSURE) only that we will rotate it 90 degrees to serve our purpose. This is the code that creates the rightButton and the transformation applied to it.

var tr = Titanium.UI.create2DMatrix();
tr = tr.rotate(90);
var drop_button =  Titanium.UI.createButton({

Now that we have the rightButton as we need it, the textField constructor becomes:

var my_combo = Titanium.UI.createTextField({
	hintText:"write your name or select one",

Please note the rightButtonMode:Titanium.UI.INPUT_BUTTONMODE_ALWAYS declaration, it makes this button visible all the time.

This is how it looks:

iPhone combobox with Titanium

Pretty sexy, isn’t it? Well we’re not done yet.

Building the modal picker

When the user focuses on the textField, the keyboard appears – so we will have to build our picker to emulate the same behaviour and to maximize the usability of our form. For this we will need a Picker and two buttons: Done and Cancel. These two buttons will be positioned in a Toolbar, again, to emulate as good as possible the keyboard behaviour.

Let’s build everything:

var picker_view = Titanium.UI.createView({
var cancel =  Titanium.UI.createButton({
var done =  Titanium.UI.createButton({
var spacer =  Titanium.UI.createButton({
var toolbar =  Titanium.UI.createToolbar({
var picker = Titanium.UI.createPicker({
var picker_data = [

The code is a little long but is not rocket science. Some stuff to talk about though:

  • Everyting is wrapped inside a view – picker_view – because we will have to animate like the keyboard does, so it’s faster to animate one element only.
  • The height of picker_view is the height of the toolbar (43px) + the height of the picker (208px). How do I know this? I just used a ruler 😀

The combobox interface looks like this:

picker Titanium for combobox

Creating the picker animation

We also need to create 2 animations: slide_in and slide_out. We will animate the bottom property of the picker_view. We will need to start with the picker_view off the screen, so we will build it with:


instead of 0 as it was initially.

var slide_in =  Titanium.UI.createAnimation({bottom:0});
var slide_out =  Titanium.UI.createAnimation({bottom:-251});

The logic behind the animations is this:

  • The user focuses the textField – the keyboard appears ( it’s done by the OS , no worries here) and if the picker_view is visible we need to hide it.
  • The user clicks the rightButton – we need to hide the keyboard and show the picker_view.

Here is the code:

my_combo.addEventListener('focus', function() {
drop_button.addEventListener('click',function() {
cancel.addEventListener('click',function() {

I also added the click event on the cancel button to hide the picker_view.

Filling the textField with the picker’s value

The only thing we have left is to actually put the value of the picker in the my_combo textField when the user clicks the done button and hide the picker_view.

done.addEventListener('click',function() {
	my_combo.value =  picker.getSelectedRow(0).title;

The getSelectedRow method of the picker is returning the selected row, and we use its title. The getSelectedRow argument is the index of the columns in the picker, and since we have only one, this is 0.

Download the project

The Resource folder of the project can be downloaded from here.

Everything is MIT licensed, but as usual, spread the word 🙂

We have an update

@CJ_Reed used this tutorial “to produce multiple selection type data entry in a single window.”
Here is how it looks like:
to produce multiple selection type data entry in a single window.
You can take a look at his code here.
Great work!

Check the Spanish version of this post:
Haciendo una lista de opciones desplegables en Titanium Appcelerator – Código y Vídeo