Appcelerator Developer Blog

Using ACS as a back-end for your App

On a previous post, I talked about consuming web services. Today I want to talk about ACS (Appcelerator Cloud Services), but before I go into what it is and how it can help you, let’s take a look at a scenario.

Your client asks you to build an App where people can create an account, log in and display a feed with photos that people have uploaded. Any user can then can snap a picture, upload it to the server and after being approved by an administrator let everyone else see it.

The App itself seems pretty straightforward.

  1. User login and photo feed are two API calls: you already know how to do that.
  2. Taking a picture is easy using the Ti.Media.takePicture method. Then another API call to upload.

Now the back-end, that’s another story. You need to:

  1. Find a server to host your back-end app
  2. Create the database, establish relations between tables (unless you’re using NoSQL Databases)
  3. Expose an API that returns JSON
  4. Create an admin interface
  5. Provide security
  6. Get ready to scale in case your App is very successful and you need more space or bandwidth

What if I tell you that with ACS you can do that right now, and maybe build your full App (front-end and back-end) in a day or two? In fact, let’s do it!

Setting up your app

Launch Titanium Studio and go to File > New > Mobile Project. Then select your Project Template. Now on the New Mobile Project screen, make sure you select “Cloud-enable this application”.

Studio has added for you the ti.cloud module, and has created two API Keys: One for production and one for development. What this really means is that you already have a back-end for your app!. Let’s check it out.

Go to my.appcelerator.com and click on My Apps; Login if you have to. You’ll be taken to a screen with a list of all your Apps. Locate the App you’ve just created and click on Manage ACS. You are now on your Adminstrative Console.

Using ACS

ACS has too many features to mention in a single post. If you want to know all there is to know about ACS, I’d suggest you go to http://docs.appcelerator.com/cloud/latest/. For our example we’ll be using two services: Photos and Users. To use ACS on your App, start by getting an instance to the ti.cloud module.

var Cloud = require('ti.cloud');

Your App already knows your API keys, so you’re ready to go. The ACS API follows a very simple pattern:

Cloud.Namespace.method({
     property1: 'here',
     property2: 'here'
},function(e){
     // I'm the callback.  The method will call me and the response object is in e
});

Both the properties for the method and the object that is returned are documented on the API reference. If you’d rather have a more tangible example, there’s a ACS KitchenSink at https://github.com/appcelerator-modules/ti.cloud/tree/master/commonjs/example.

User Login

For simplicity, I will not implement a way of creating a new user from the App. I’ll assume that the user is already created. To create a new user, scroll down on your ACS console, click on “Users” and then on “Create a New User”.

Fill out Email, Username, Password and Password Confirmation, and click “Submit”. Now you have a user on the system and you’re ready to login. As explained on the API documentation, and based on the simple pattern described earlier, you can call the login method sending two properties: Login (can be email or userid) and Password. Upon successful login you’ll receive an object with data for this user.

Success Example:

Error Example:

PRO TIP: On Titanium you can do console.log(JSON.stringify(your_object)) to inspect the contents of the object that was returned. Here I’m taking that response and viewing it on jsoneditoronline.org

This means that your Titanium code may look something like this:

function doLogin(e){
     Cloud.Users.login({
        login: $.uid.value,
        password: $.pwd.value
    }, function (e) {
        if (e.success) {
            var win=Alloy.createController('feed').getView();
            win.open();
        }
        else {
           alert(e.message);
        }
    });
}

The Photo Feed

To implement the Photo Feed, we use the “query” method in the Photos namespace. This method can receive many optional parameters. We’ll only use one for retrieving the results in reverse order, so we do -created_at; the minus sign reverses the order. The method will return an object will all the photos.

Example Success

As you can see, ACS has already created 6 different versions of your photo: square_75, thumb_100, small_240, medium_500, medium_640 and large_1024.

PRO TIP: Paging is supported using the “page”, “per_page”, “limit” and “skip” parameters, so implementing “lazy loading” is just a matter of writing the front-end code.

To display the feed is as simple as looping through the “photos” array. Your code may look something like this:

    Cloud.Photos.query({
        order: "-created_at"
    },function (e) {
        if (e.success) {
            if (e.photos.length == 0) {
                // no photos
                alert('There are no photos');
            }
            else {
                e.photos.forEach(function(item){
                    // work with this photo
                })
            }
        }
        else {
            alert(e);
        }
    })

Uploading Photos

To upload photos we use the “create” method, which receives the photo in binary form in a property named “photo”. You may get the photo from the photo gallery using Ti.Media.openPhotoGallery or from the camera using Ti.Media.takePicture. Once you have the photo, you may call the “create” method something like this:

     Cloud.Photos.create({
          photo : event.media
     }, function(e) {
          if(e.success) {
               // reload the feed?
          } else {
               alert(e.message);
          }
      });

So there you have it. You very own secure and scalable cloud-based back-end! I have built a proof-of-concept located at github.com/ricardoalcocer/tiphotogram. Here’s how it looks.

I’ve thrown in some bonus conditional Alloy code to use Toolbars on iOS and ActionBar on Android.

This is not a finalized app, just a quick example of you can quickly put together an Alloy-based front-end with an ACS back-end. Feel free to use, fix and improve upon it.

Final thoughts

You can use ACS with or without Titanium, so if you’re looking for a back-end for your web-based app, ACS may be what you’re looking for. For this example we used the ACS SDK for Titanium, but you could also use the native iOS or Android SDK as well as the REST API. ACS offers 20 pre-build services, one of which is Custom Objects. This means that you can create your own data-sets, with your own data structure, and automatically get a REST API to interact with them.


Please Review ListView Phase 2 specification

Last month as part of our 3.1.0 release we introduced a new, faster version of TableView called ListView. As a refresher, it has several key features:

  • Data-oriented vs view-oriented architecture
  • A separate module. Does not replace the existing TableView so you can migrate on your schedule
  • Extremely performant

We’re now working on phase 2 of that implementation. Please review the specification and add your comments by EOD 5/15 (Next Wednesday).

Link: https://wiki.appcelerator.org/display/community/Titanium+ListView+Specification


Featured Developer – Lark Cookbook

Our featured developer spotlight this week comes from Jared Stoneberg. Jared and his web development company, Number 10 Web Company, leveraged a Kickstarter campaign to help fund the beautiful Titanium app “Lark – Cooking Against the Grain”. Read more about how Jared and team pulled together this app to showcase the favorite recipes of James Beard Award-winning Chef John Sundstrom.


Lark icon

Tell us a little bit more about your product and app
James Beard Award-winner and Food & Wine Magazine Best New Chef John Sundstrom takes you on a culinary journey through the Pacific Northwest. His Seattle restaurant, Lark, is a beloved institution, and in this app, he shares 144 of his favorite recipes, all lushly illustrated with full color step-by-step photographs and beautiful HD video demos and vignettes (video | iTunes). Organized according to three distinct seasons – Evergreen, Bounty and Mist – the app is an homage to the majesty and bounty of the Northwest. Rich in detailed instruction, inspiring recipes, and stunning images, this app is a must-have for all home cooks.

Lark cookbook

Why did you decide to use a mobile development platform instead of developing with the native SDKs?
We are a web development shop that has seen a growing number of requests from our clients for native app development over the last 2 years. Our decision to use Titanium allowed us to put to work the Javascript expertise we use everyday in web development to build native applications and for us that is very valuable.

Why did you pick Titanium for your development needs? What other platforms did you consider?
We also explored Phonegap/Cordova. Our experience was that when rendered on the device the experience felt nicer with Titanium. We also wanted to be able to have more complex controls, and performance seemed to suffer when we built these in HTML5. We took a short dead end path into using phonegap, but quickly realized it was not going to be suitable for our application requirements.

What Titanium modules did you use in your app? Did you develop any of your own modules?
As we were developing a cooking app, we were most concerned with the quality of the content. Our editorial team was also widely distributed, with the Author and Chef developing the recipes, his staff turning them into things a normal person could cook at home, and a large panel of testers cooking (and eating) the results. We had folks all over the US, and even an editor in London helping out. As a result we need a good toolset for data entry and management. The Drupal tools we use for our normal web development allowed us to build an online data entry site for everyone to use as a collaborative tool.

Then we extended the site using a Drupal query builder called Views so we could expose the data directly to Titanium via a REST interface with endpoints on the recipe data set. On the Titanium side, we chose to use a module called JSONDB (deprecated now in favor of SculeJS) for local data storage since it provided a familiar MongoDB style of interaction. During data entry and content testing we ran regular exports from the site so we could develop against a “real” data set. Once the data was finalized it was a simple matter of importing into the local database, knowing we had already found most of the edge cases during data entry.

Can you walk me through how you developed this application?
Early on in the process we realized that implementing our interface design was going to present some major performance challenges. The book is broken up into “plates” each of which consists of one or more recipes, and each recipe has multiple steps. Each step is made up of a large number of views, with up to 5 variable length text items, and dynamically determined spacing for controls on each step.

While displaying some of this complex data we experienced significant lag that caused a poor user experience. Drawing these steps means calculating text lengths dynamically, and the combined rendering and redraw time after the length could be calculated was unacceptable. Our solution was to create a second “render robot” app from the same code base, that ran through the entire data set, rendered the displays, and stored the heights/lengths of all the steps in a JSONDB table. We then were able to use that table to display the steps in the real app using absolute measurements, which resulted in a massive improvement in performance even on the most visually complex screens! See a short video here of this in action here:

LARK – Cooking Against the Grain iPad App Demo from Lark Cookbook on Vimeo.

A short tour of the iPad cookbook app with a look at the Chocolate Madeleines recipe.


Big thanks to Jared for taking the time to give us some insight into his experience and success with Titanium app development. Interested in having your Titanium app showcased? Send us an email at community@appcelerator.com and share your story with us!


Beginners: Javascript Objects and Arrays

If you’re new to Titanium, first of all Welcome!

If you are just starting out with Javascript, this post will definitely help you understand two very important features of Javascript: Object and Array literals. Knowing their syntax will not only help you understand how Titanium works, but will speed up your understanding of CommonJS and JSON.

Perhaps you don’t know them by name, but the truth is that when you work with Javascript, you’re working with Objects all the time without realizing it. Take a look at the following example:

var carmake='Honda';
console.log(carmake.toUpperCase());

Where did toUpperCase come from? Here you have used an Object. Every time you create a String variable, you’re actually creating a String Object. This object has properties and methods, toUpperCase being just one of them. More details about the String object here. Get used to the word “Object”, because is the foundation of modern programming.


Object Literals

Object Literals are Objects that you create on the fly. The syntax for Object literals is simple:

  • Enclose it in curly brackets
  • separate properties with comma
  • separate keys and values with a colon
var person={
    name: 'jack',
    email: 'jack@ctu.com',
    twitter: '@jackb_ctu'
};

To access the values on this object, you can use “dot notation”, that is, the name of the object, a dot, and the name of the property.

console.log(person.name);
console.log(person.twitter);


Array Literals

Just like objects, arrays can also be created on the fly. The syntax rules for array literals:

  • Enclose it in square brackets
  • separate each element with comma
var arr=[
            'value1',
            'value2',
            'value3'
        ];

To access the values, you use a numerical index:

console.log(arr[0]);


The fun part

The power of Javascript Object and Array literals comes by combining them. A combination of Objects and Arrays make up a complex, multidimensional object.


Array literal with two objects as values

var arr=[
           {key1:'value1'},
           {key2:'value2'}
        ];
console.log(arr[0].key1);


Object literal with a two-item array as property

var obj={
            key:[
                   'value1',
                   'value2'
                ]
        };
console.log(obj.key[1]);


Array literal with one property that is a two-item array

var arr=[
           {
              key:[
                    'value1',
                    'value2'
                  ]
            }
         ];
console.log(arr[0].key[1]);

This syntax is very popular in today’s web services and perhaps you’ve heard of JSON (Javascript Object Notation). JSON is an implementation of this syntax designed to be a way of transporting data across the Internet.


Applying these concepts in Titanium

Titanium itself is a JavaScript SDK (Software Development Kit) that works as an “Object Factory”. This means that it has methods that generate Objects, and most of the times these methods receive Objects as arguments. It sounds more confusing than it is.

var win=Titanium.UI.createWindow({
    backgroundColor: '#fff',
    fullscreen: true
})

The result of this operation is a Titanium Window Object stored in the variable win. However, the createWindow method received an object as argument, and object with the properties backgroundColor and fullscreen. As you can see, knowing how an object is constructed allows you to understand that the createWindow() and the toUpperCase() methods are very similar. The difference is that you are sending an Object Literal to the createWindow method.

A full description of Titanium’s objects can be found at Titanium API Documentation.

I hope this short tutorial can help you understand Titanium’s syntax and how powerful it can be.

Codestrong!


Making it easy to port your apps to Tizen: A promotion from appbackr for Titanium developers

The following guest spot is from Trevor Cornwell, Founder and CEO at appbackr. You can follow him on Twitter at @trevorcornwell


Titanium makes it easy for developers to build mobile apps and publish them across platforms. It is a big step forward. appbackr is focused on motivating more developers to build across newly emerging platforms.

Encouraging distribution to other platforms is challenging because of a few basic reasons, starting with “Is it worth my time to port to any given new platform?” Because selling apps, like any content, is a matter of aggregating medium and long-tail users, we believe that porting to a new platform makes sense. Except that there are tedious sign-up processes, long contracts that may subsume distribution rights and unknown SDKs, which all create just enough friction to make the process eminently skippable.

And the problem exists on the other side: new platforms want great apps, but not necessarily sub-prime, chop-shop apps.

So how do great developers with the best new apps meet great, emerging platforms efficiently?

appbackr is providing a promotion to Titanium developers to help! We’ve made it possible for every app that you create to get scored for quality and relevance on a 1 to 10 scale. The best apps receive tools and a guarantee number of downloads based on the store’s needs and how well your app fits.

As part of this promotion, once you build your app on Titanium, you can see the score and your offer. With the announcement of Titanium’s support of Tizen, appbackr has scored every app and Titanium developers will be receiving a simple 3-step process for porting to Tizen and getting a minimum guarantee for your app.

You can also sign on to Xchange and track your installs on one dashboard and even consolidate payments so you don’t have to provide your bank account information to every new platform that asks for it.

Why Tizen? This is a chance to have your app, live, right from the start of a brand-new operating system built on HTML5 and part of the Linux Foundation. It has heavy support from Samsung, Intel and major carriers around the world.

And once your app is live in Tizen, we can give you additional offers like free translation into launch country languages, and even offers to port to additional HTML5 platforms that are relevant to your app.

You made a great decision building with Titanium. Your app is ready to go in Tizen. Now, submit it through Xchange and receive the financial incentives that your app deserves.

Page 2 of 9112345...102030...Last »