The Titanium Mobile SDK, one component of Appcelerator’s mobile development platform, is the leading solution for building cross-platform native applications. Titanium Mobile provides a high-level, cross-platform JavaScript API for mobile development, using the native APIs and user interface frameworks for iOS, Android, and browser-based applications. With over 320,000 registered developers and more than 40,000 applications deployed to native app stores, Titanium has enabled developers and designers from many different backgrounds to quickly develop and deploy high quality mobile applications.

While Appcelerator provides a number of integrated cloud services for use along with Titanium Mobile applications (like push, data storage, image uploads, etc.), there is a tremendous amount of demand in the market today for integration with Force.com and Salesforce data. Thanks to the REST API exposed by Force.com, integrating this data into Titanium applications is pretty easy. This tutorial first teaches you about Titanium Mobile at a high level, then explains how you can use the Force.com REST API from within a Titanium application.

Titanium Mobile App Fundamentals

Most developers creating mobile apps with Titanium develop for all platforms using Titanium Studio, our free Eclipse-based IDE. Titanium also requires the installation of the native development tool chains for iOS and Android if you intend to target one or both of those platforms.

Step 1: Install and Configure Titanium Studio

Install and configure Titanium Studio, with the native SDKs, following the instructions found at http://docs.appcelerator.com.

Step 2: Create a New Mobile Project with Titanium Studio

Once Titanium Studio is open, create a new project using the appropriate wizard in Titanium Studio.


Titanium-001.png


There are many project types available, but choose a Titanium Mobile project and click Next.


Titanium-002.png


Next, configure the details about the project, such as a name, a reverse-domain identifier (used for app store distribution), and desired target. Once you fill in the required fields, click Finish to generate your mobile project.


Titanium-003.png


Step 3: Take a Tour of Your New Titanium Mobile Project

Your new mobile project has the following structure:


Titanium-004.png


tiapp.xml is the primary configuration file for a Titanium application. This is where you store Force.com access credentials.

You store all the JavaScript source code, images, and other assets that ship with your Titanium application in the Resources directory. This directory contains app.js. This is the “bootstrap” file for the application – the device evaluates the JavaScript code in this file at runtime, and creates the application’s user interface and functionality. Of course, applications are typically broken up into multiple files for modularity and clarity. You accomplish this by creating CommonJS modules, similar to the node.js programming environment. This tutorial explains how to create such modules a bit later on.

Step 4: Learn the Basics of Developing Titanium Mobile Apps

Just to ensure that you understand the basic principles of writing Titanium applications, create a very simple program in app.js that illustrates the basic programming techniques in Titanium Mobile. Replace the default code in app.js with the following snippet:

  var win = Ti.UI.createWindow({
  	backgroundColor:'white'
  });

  var view = Ti.UI.createView({
  	backgroundColor:'red',
  	height:100,
  	width:100
  });
  win.add(view);

  view.addEventListener('click', function() {
  	view.animate({
  		top:10,
  		left:10,
  		duration:500
  	});
  });

  win.open();

This code creates a very simple application that draws a red box in the center of the screen. Native user interface components for the underlying platform create the UI in a Titanium application, not HTML and CSS (unless, of course, you’re running the mobile Web SDK in the browser) – so your app looks and feels the same as any other native application. When you run the app in the iPhone and Android simulators, the UI looks like this:


Titanium-005.png


Functions in the Titanium.UI JavaScript namespace create user interface components. (“Titanium” and “Ti” are aliases to the same object – “Ti” is usually used for brevity).

A window object is the top-level container for a Titanium application. Every app has one or more windows. The code example above creates one window, which “opens” to display the user interface of the application.

A view is the most primitive UI component, analogous to a “div” on an HTML page. It is a block of content drawn on the page. There are special types of views, like TableView, ImageView, and ScrollView, which are useful for more specialized use cases, like displaying data or images. To display a view, you have to add it to the view hierarchy. You accomplish this by using the add function, which exists on the vast majority of user interface objects.

You can instrument almost every object in Titanium with event handlers to react to user input, sensor data from the device, or custom events that your program emits. To respond to these events, you can use the addEventListener function, present on most Titanium objects. In this simple example, you app listens for a “click” event to the view object. The second argument to addEventListener is a JavaScript function that executes when there is a “click” event on the view. In this example, a click causes the view to animate to the top left corner of the screen.

While this small sample app barely scratches the surface of the Titanium API, it illustrates the basic concepts of Titanium user interface programming. In summary:

  • You create native user interface objects in JavaScript, using functions in the Titanium.UI namespace.
  • You assemble UI components in a parent-child relationship to form a view hierarchy, which the app draws on the screen.
  • You instrument UI components (and other Titanium objects) with behavior using addEventListener

You can find a full listing of the Titanium API at http://docs.appcelerator.com.

Force.com Remote Access Configuration

Once you have a free Developer Edition org of Force.com, you must configure a Remote Access application before you can connect the example Titanium application the Force.com back-end. You can find extensive documentation on enabling your application for Remote Access on Developer Force, but I found this deep dive on OAuth 2.0 to be most useful. Not only does it cover how the Force.com OAuth 2.0 implementation works, it also describes how to set up an application for remote access.

After you successfully configure remote access for the application, you have a corresponding Consumer Key and Consumer Secret, which are used for the OAuth authentication process:


Titanium-006.png


NOTE: When configuring remote access, salesforce.com provides a callback URL that native applications can use, which consume OAuth without having a Web-based back end. Please use https://login.salesforce.com/services/oauth2/success as your app’s callback URL during configuration.


Titanium Mobile Apps with Force.com

What follows is a tutorial in which you develop a very simple JavaScript module to authenticate your application against the Force.com REST API. You can clone or download the example application from GitHub, which demonstrates basic usage of the REST API via a Titanium JavaScript module.

To get started with the example project, complete these steps in Titanium Studio:

  1. Click File | Import | Git | Git Repository as New Project.
  2. For URI, enter git://github.com/appcelerator-developer-relations/Force.git and then click Finish.

Once the import finishes, the example project is now ready to use.

Running the example application shows a series of API calls that exercise the salesforce.com REST API. You can find the official REST API documentation, along with all available options and queries, here.

Before the Titanium app can function with Force.com, you must configure a Remote Access application’s Consumer Key and Consumer Secret in tiapp.xml. Copy these values from the information page for your Force.com Remote Access application, return to Titanium Studio, double-click the tiapp.xml file, and switch to Source View:


Titanium-007.png


There, look for the following XML properties and substitute your values for "XXX":

<property name="force.consumer.key" type="string">XXX</property>
<property name="force.consumer.secret" type="string">XXX</property>

Building Blocks

The following sections provide you a tour of the key building blocks in the example app's code.

Block 1: Require the Force.com Module

To use the Force.com module, force.js, you must require it in the JavaScript code. See app.js:

var force = require('force');

Block 2: Establish an OAuth Session

The Force.com JavaScript module is in the Resources directory of the example application. Before using the module, ensure that you have a valid OAuth session. You can do this using the force.js module’s authorize function. See app.js:

force.authorize({
success: function() {
//called when a valid session is achieved
},
error: function() {
//called on any error
},
cancel: function() {
//called if the user cancels login
}
});

Block 3: Authorize the Application

To authorize the Titanium application, it displays a Web view that prompts the user for a salesforce.com password. Once the user provides this, the force.js module has the necessary access token to make authenticated API requests on behalf of the user. You'll see the following when you run the example app.


Titanium-008.png

Block 4: Make Requests via REST

To make requests against the REST API, the app uses the request function. See ui.js:

force.request({
  type:'GET',
  url:'/sobjects'
  /* data: {}, // for POST/PUT */
  callback: function(data) {
    //deal with data from the server
  },
  onerror: function() {
    recover from a server error
  }
});


Using these basic building blocks, you can assemble a very simple application, which pulls in a list of accounts from the standard object, Account. The app lets you create new accounts by name, and supports editing the names of existing accounts. The final product, side by side on iOS and Android, looks like this:


Titanium-009.png


There’s quite a bit of code in the ui.js file in the Resources directory to create platform-specific user interface components for both iOS and Android. Which brings up another important point about Titanium – it is not intended to be a “write once, run everywhere” type of solution. Rather, you expose platform-specific UI elements to provide your users a “best in class” native app experience.

A case in point: This application makes use of the common UINavigationController component on iOS via Titanium.UI.iPhone.NavigationGroup. This creates a stack of Titanium windows that slides nicely back and forth with native animations. On Android, you arrange windows as a stack of activities, and expose the Add functionality via the hardware menu button. Our app also works seamlessly with the Android back button.

Notice that most of the code across platforms is similar, but there is Boolean branching logic to provide the right behavior per platform. Doing this to some extent is typical (and encouraged) in a Titanium application.

Conclusion

In this simple tutorial, you learned the basics of the Titanium platform, and how to communicate with salesforce.com via its REST APIs. While this example was pretty minimal, the entire range of salesforce.com APIs are easily accessible in Titanium Mobile applications using the force.js module. Thanks for reading, and code strong!

About the Author

Thanks to Kevin Whinnery at Appcelerator for his contribution to Developer Force.

Related Resources