Titanium 2.X
Integrating with Appcelerator Cloud Services

Integrating with Appcelerator Cloud Services

Objective

In this section, you will learn how to utilize the Appcelerator Cloud Services (ACS) API, previously known as CocoaFish, for your mobile apps.

Contents

Appcelerator Cloud Services (ACS) provide a wide array of automatically-scaled network features and data objects for your app. Tasks such as push notifications, user logins, photo uploads, checkins and status updates that usually require server programming or tedious integration with multiple SDKs are performed through one simple interface.

We worry about the database, file storage, search engine and application stack so that you can focus on what’s really important: your app and your users. As usage of your app increases, ACS scales up automatically to handle the load without requiring you to do any additional work. Photos and other files are redundantly stored on multiple devices across multiple storage facilities, preventing data corruption and loss.

Over 25 APIs are available for immediate use in your app to provide the most popular network features. Writing, testing, and deploying server code is a thing of the past. Focus on your users and app features by using any combination of the following APIs:

  • Push Notifications

  • User management

  • Photo manipulation and storage

  • Places (rich location storage)

  • Social integration

  • File Storage (since SDK 2.1.1/module version 2.2.0)

  • Check-ins

  • Status updates

  • Chats

  • Friend connections (since SDK 2.1.1/module version 2.2.0)

  • Ratings and Reviews

  • Discussion forums

  • Event planning (since SDK 2.1.1/module version 2.2.0)

  • Messaging (since SDK 2.1.1/module version 2.2.0)

  • Key-Value data storage

  • Access control lists (since 2.1.0)

ACS API support

Note that when new APIs are added to ACS, they may not be immediately available in the Titanium.Cloud module.
The since version listed after some APIs indicates the Titanium Mobile SDK release that included support for
that API. (Note that the Titanium.Cloud module version is not always the same as the SDK version that it ships with.)

ACS is open to all app publishers, regardless of the development technology used to build the app – Titanium, Objective-C, Java, or HTML5 via frameworks like Sencha Touch or PhoneGap – we’ve got you covered. Appcelerator Cloud Services provide a complete REST API along with iOS, Android, Javascript and Actionscript SDKs. Any device that can make HTTP requests over the Internet can securely use ACS as its server backend.

Integrating ACS into your app

To integrate ACS into your app, you'll need to follow these four general steps:

  1. Register your app with Appcelerator Cloud Services

  2. Configure your Titanium project to use ACS

  3. Authenticate your API calls to the ACS cloud infrastructure

  4. Implement the Titanium ACS API calls within your app

You might want to add a fifth step to this list: Manage the data your app collects by using the ACS control panel or RESTful API.

Step 1. Register Your App with Appcelerator Cloud Services

Using Appcelerator Cloud Services API to store and retrieve data for your app is easy. Applications are automatically registered with ACS when they are created in Titanium Studio, if you tick the "Automatically cloud-enable this application" in the New Titanium Project wizard, and then can be viewed on the My Apps page of your account.

Alternatively, the app can be manually registered on the My Apps page by clicking the "Register a New App" link and specifying the app name and description. A unique OAuth Consumer Key, OAuth Secret, and App Key will be automatically generated. These values are then used within your app's code.

Step 2. Configure your Titanium project

ACS support is baked into Titanium. However, you must include the cloud services module into your project to use ACS functionality. In your app.js (or other suitable file), include the require() statement as shown here:

var Cloud = require('ti.cloud');
Cloud.debug = true;  // optional; if you add this line, set it to false for production

In order for the ti.cloud module to be recognized, ensure that the modules directive has been added to tiapp.xml.

<modules>
    <module platform="commonjs">ti.cloud</module>
</modules>

Step 3. Authentication

Your app must prove that it is allowed to talk to ACS. This keeps your data secure by preventing anyone from making requests to ACS that impersonate your app. There are several methods for authenticating with ACS:

  • 3-Legged OAuth

  • 2-Legged OAuth

  • API key

3-Legged OAuth, in which the username and password are not stored by the application, is the preferred method in most cases. See the Titanium.Cloud Module Reference for details on using each of the mechanisms in Titanium. For more information, see Authentication in the ACS docs.

Each of the authentication methods requires a key or other data identifying your ACS application.

If you add ACS support to your application when you create it in Titanium Studio, Studio adds the authentication keys to your `tiapp.xml` file. If you create an ACS application on the ACS web site, and want to add support for it to a Titanium project, you can add its keys to your `tiapp.xml` file:

tiapp.xml
<property name="acs-api-key" type="string">get_from_app_admin_page</property>
<property name="acs-oauth-key" type="string">get_from_app_admin_page</property>
<property name="acs-oauth-secret" type="string">get_from_app_admin_page</property>

Step 4. Implement the Titanium ACS APIs

This is the magic, of course. This is where you add cloud services to your app using our APIs. With over 25 APIs available for you to use, we obviously can't cover them all here. But let's take a look at a couple of examples.

Create a user
// example assumes you have a set of text fields named username, password, etc.
Cloud.Users.create({
    username: username.value,
    password: password.value,
    password_confirmation: confirmPassword.value,
    first_name: firstName.value,
    last_name: lastName.value
}, function (e) {
    if (e.success) {
		// user created successfully
    } else {
        // oops, something went wrong
    }
});

Create a user using 3-legged OAuth
// ACS app must be configured to use 3-legged OAuth
Cloud.Users.secureCreate({
    title: 'Sign Up Here'
}, function (e) {
    if (e.success) {
        alert('Success:\n' +
            'accessToken: ' + e.accessToken + '\n' +
            'expiresIn: ' + e.expiresIn);
    } else {
        alert('Error:\n' +
            ((e.error && e.message) || JSON.stringify(e)));
    }
});

Post a photo
// assumes you've obtained a photo from the camera or gallery, with blob data stored in an object named photo
// collectionID is an ID generated by ACS for a grouping of photos, you could retrieve via code or hard-code it
Cloud.Photos.create({
    photo: photo,
    collection_id: collectionID,
    'photo_sync_sizes[]': 'small_240'
}, function (e) {
    if (e.success) {
		// null out our photo objects to clean up memory
        photo = null;
        collectionID = null;
    } else {
        // oops, something went wrong
    }
});

Linking a Facebook login with your app
// Not shown is the code to implement the Facebook module in your app

// call the ACS Facebook SocialIntegrations API to link logged in states
function updateLoginStatus() {
    if (Ti.Facebook.loggedIn) {
        label.text = 'Logging in to ACS as well, please wait...';
        Cloud.SocialIntegrations.externalAccountLogin({
            type: 'facebook',
            token: Ti.Facebook.accessToken
        }, function (e) {
            if (e.success) {
                var user = e.users[0];
                alert('Logged in! You are now logged in as ' + user.id);
            }
            else {
                error(e);
            }
        });
    }
    else {
        label.text = 'Please login to Facebook.';
    }
}

// when the user logs into or out of Facebook, link their login state with ACS
Ti.Facebook.addEventListener('login', updateLoginStatus);
Ti.Facebook.addEventListener('logout', updateLoginStatus);

// add the Facebook login button
win.add(Ti.Facebook.createLoginButton({
    top: 10
}));

Of course, there are many more examples we could show. Instead, head on over to the API documentation to view the samples included there plus the full explanation of ACS APIs.

The Titanium.Cloud module also includes a sample application demonstrating each of the ACS request types. You can find this in the modules folder under the Titanium SDK folder. For example:

/Library/Application Support/Titanium/modules/commonjs/ti.cloud/<version>/example

Step 5. Managing your app's data

Of course, there's no sense in collecting data if you don't use it. Data created by your app is stored within the Appcelerator ACS cloud. You can view and manage this data through the ACS administrative web site. You can also use the RESTful API (or any of the other APIs) to extract the data you need.

Step 6. Sharing ACS Objects

Starting in Release 2.1, The Titanium.Cloud module supports ACS Access Control Lists (ACLs) to control access to ACL resources. An ACL lets you grant read and write access to users other than the owner of an ACS object. An access control list controls read and write access to any ACS objects it's attached to. For ACS, read and write permission are defined as follows:

  • Read permission. Includes the ability to show, query and search ACS objects.

  • Write permission. Includes the ability to update and delete ACS objects.

An ACL can include:

  • A list of user IDs granted read permission.

  • A list of user IDs granted write permission.

  • A public read flag granting read permission to all users.

  • A public write flag granting write permission to all users.

The object's owner always has read and write permission.

You can specify an ACL when you create or update an object.

Currently, ACLs can be used with the following ACS objects: Checkins, Custom Objects, Events, Files, Photos, Photo Collections, Places, Posts, Reviews and Statuses.

See Ti.Cloud.ACLs for methods to create and update ACLs.

References

Summary

In this section, you briefly explored how to use the Appcelerator Cloud Services (aka CocoaFish) API in your mobile apps.