Appcelerator Developer Blog

Appcelerator Participates in NASA’s International Space Apps Challenge

Last month, NASA hosted the International Space Apps Challenge – a 48-hour hackathon that invited citizens from around the world to collaborate to create open-source solutions for problems NASA faces both in space and here on Earth. NASA released a list of more than 50 challenges for hackathon teams to tackle, including a wide range of topics such as solar flare, star maps, space stations and renewable energy. Teams could sign up to participate virtually from anywhere  in the world.

We are proud that a few teams from the Appcelerator community participated in the International Space Apps Challenge, and we are excited to showcase their work. Great job, everyone!


by Ketan Majmudar

Project: T-10 (pronounced “T-Minus Ten”)

Team (Appcelerator community):
Kate Arkless Gray @SpaceKate
João Neves @jpgneves
Ketan Majmudar @ketan
Dario Lofish @dariolofish

The Challenge: Spot the Station

NASA recently launched the Spot the Station website, which allows people to spot the space station and sign up for alerts when it flies overhead. The tasks were to:

  • “Extend the functionality of the Spot the Station site by building an app that allows you to share your sightings with others.”
  • “Create a visualization with Spot the Station data.”

The Solution:

T-10 from João Neves on Vimeo.

Overview

Our goal was to set up an alert to help astronauts on the International Space Station (ISS) take images of planet Earth under their specific desired circumstances. For example, they might want a picture of London with clear skies or a picture of New York during a thunderstorm.

The T-10 app allows astronauts to select cities of interest, time of day and the weather condition required. This data is then sent to our server, which waits for the correct conditions and finds the next scheduled times the ISS will be over the city in question. When both city and weather conditions are met, a push notice is sent to the app and provides an alert 10 minutes before the ISS will enter visibility of that city, giving astronauts enough time to prepare to take the photo.

When the T-10 countdown begins, it also sends a push alert to any ground users who have the app installed and would like to send a digital wave back to the ISS and the astronauts aboard. This two-way communication creates a social connection and sense of unity, promoting the knowledge that people on Earth and in space are waving at each other.

In future updates, we hope to add the ability to add the #ISSWave hashtag to share pictures to and from the ISS and Earth. We also intend to add more complex controls to manage when and how alerts get stored and shared with others.

Getting Started

I signed up for the International Space Apps Challenge in London, held at the Google Campus in East London. I had been invited to take part in a European space apps hack recently, but due to working commitments, I completely missed it. When I saw the announcement for the International Space Apps challenge, I signed up as quickly as I could. Being a NASA-driven event just added to the awesomeness of the hackathon. My main goal was just to participate, and I wasn’t even intending to take part seriously in the challenge aspect. I was more than happy to network and tinker with some cool ideas and people over the weekend.

A very early start on Saturday morning was a challenge in itself, having been up late every night for the past two weeks working on the SCI-FI-LONDON film festival app, but I felt it was my duty to make the effort for this hackathon. To be honest, I didn’t know what kind of people would be present or if I would have the energy to stick through a whole weekend. I went in expecting to build an app using the Patino game engine for Titanium, as I’m on the private beta – perhaps a cosmic windchime or mapping related to a comet or near-Earth object. But in the midst of the opening pitches and the multitude of available broad challenges to choose from, fate and social connections led us to form our team and the app T-10.

I tweeted Kate Arkless Gray (@SpaceKate) – whom I’d met through Bill Thompson (@billt), a technology journalist who works for the BBC Click Radio programme – and we connected with an idea to build an alerting app system which related to current earth weather patterns. Although my original idea was more Earth-bound, Kate had actually asked astronauts from the ISS if they would use an app that would tell them when the weather was good so they could take snaps of the planet! This was a cool plan, and we set it in motion.

Kate’s friend Joao Neves (@jpgneves), a software engineer and Android hacker from Stockholm, came on board, and we decided to use Titanium as the core of the application and build a server component. What I most enjoy about the Titanium platform is that it allows me to take the foundation of my learned skill sets and apply it to something amazing that is inclusive within the mobile community. Targeting multiple platforms is awesome, and being JavaScript-based, Titanium has helped me embrace the language in a way I never would have before.

The Process

We had to make sure we had the right APIs on hand and a suitable user-flow. We found a table that would be our home for the next 12 hours and had an open recruitment office in the form of stickies on the edge of our table. We sat and began coding an app that would use ACS push notifications and a bunch of open-source Titanium scripts. We had so much fun building, designing and conceptualising the app and solution that we wanted to weave a few more ideas in, knowing that we could never achieve the Flickr pool upload, share integration and Earth-based “wave” functionality that would enable people on the ground to send a virtual wave to the ISS as it flew over.

When our fourth team member, designer Dario Lofish (@dariolofish), logged on, our dream team was complete. We all connected online, made sure we were in tune with the concept and approach, then got back to our roles.

As fate would have it, the ISS was due to fly over London at around 9:30, and Kate dragged us (plus about 10 others) so we could see it fly over. Then back to the hacking. Under normal circumstances, we would have stayed all night, but by 22:30, I bailed to the far recesses of North London, promising to return the following morning.

App design during hackathons can be crazy, but we managed to have clear roles and had a simple core concept that we were all behind. Titanium made it easy to prototype ideas and integrate design ideas on the fly quickly.

Highlights & Insights

Our demo at the end of the day went really well, and I demonstrated the functionality of setting and sending the event from my iPhone 4S plugged directly into the projector, with push notification responses. It was a real joy to be part of the team behind T-10, and I’m proud of the ease and speed with which our team locked into the development process and how easy we made all of our jobs seem.

I was pleased to see a lot of mobile solutions come out of the weekend, many of them trying to take complex space data and put them into the hands of ordinary people in a way that makes sense. There were some superb, inspiring solutions that bridged the gap between software and hardware. It was also incredible to see the cooperation and coordination of people, some in the same room, some located all over the world. Since I was 10, I have had this odd dream to become a developer – back then it was just a desire to be a computer programmer. Mobile development has suddenly become a huge business and one that has moved in from the fringe of society into an evolving and ever-shifting set of features and parameters. With every year, new concepts, gestures and devices evolve and play a role in how our societies interact with the world around us. It is very cool and exciting to be part of that change.

At the end of the hackathon, we were so excited when they announced that we had been chosen by the judges as one of the two winning London Challenge teams! We are hoping that we will do well in the global round coming up and that our app will be featured in the Victoria and Albert Museum as part of the Digital Futures: Urban Open Space event.

We are now in the People’s Choice voting phase, so you can vote for T-10 via Twitter. Wish us luck!


Appcelerator Node.ACS Financial Stock Watch List

Implementing a Financial Stock Watch List may seem pretty straightforward at first, but optimizing it for mobile in the most efficient way possible presents a few challenges. Today, I’d like to walk you through how you can use the Appcelerator Mobile Platform to streamline API calls and data over the wire for your mobile applications leveraging remote data sources.

Appcelerator Custom Cloud Service (Node.ACS) allows Node.js based custom services to be published into the cloud and can be used to create a middleware tier to expose mobile-optimized web services to your application.

Instead of making multiple calls from the Titanium mobile client directly to the stock quote web service, we will create a Node.js service which will make multiple calls to a back end Stock Quote web service over the high speed internet and present aggregated data to the Titanium mobile client. The Titanium mobile client can then make a single mobile optimized web service call to Node.ACS over the slower cellular network to retrieve the Stock Watch List data. Furthermore, since the Watch List only displays 3 data values from the 13 provided by the stock quote web service, a substantial reduction in overhead is achieved which results in improved user experience and reduced data transmission.

The Problem

The mobile watch list we are trying to create is shown below:

The Stock Watch List displays a list of Stock Symbols as well as the Last Price and Change (from the prior day) for each stock symbol in the list. The “As of” time and date is useful to display as well so the user can see when the stock data was last retrieved.

The stock web service used in this example is from Markit On Demand.

In order to implement the watch list, repeated calls to a stock quote web service needs to be made; one call for each stock symbol the user is “watching”. The data then needs to be assembled and applied to a list control (i.e. TableView).

Below is an example of a stock quote REST web service call and JSON reply from MarkitOnDemand for the stock symbol AAPL (Apple Inc):

Call:

 

http://dev.markitondemand.com/Api/Quote/json?symbol=AAPL

Reply:

{
	"Data":{
		"Name":"Apple Inc", "Symbol":"AAPL", "LastPrice":424.04,
                "Change":-3.36899999999997,
		"ChangePercent":-0.788237964104632,
		"Timestamp":"Tue Jan 22 10:58:00 UTC-07:00 2012",
		"MarketCap":395266765800,
                "Volume":263809,
		"ChangeYTD":402.64,
                "ChangePercentYTD":5.31492151798133,
                "High":424.99,
		"Low":423.22,
		"Open":424.86
	}
}

From the reply above, you can see that we only need 3 of the 13 values returned by the web service for our watch list: LastPrice, Change and Timestamp. While these calls can be made from the Titanium mobile client, there is a large amount of overhead due to the unused data returned by the web service. Also, these calls are made across the often slow and unreliable cellular network as illustrated in the diagram below:

SOLUTION

One solution to this problem is to change the application architecture so that the watch list is retrieved by Appcelerator’s Node.ACS Platform as a Service (PaaS). Then the Titanium mobile client only needs to make one web service call to Node.ACS to retrieve the watch list data. The Node.ACS service makes the repeated calls to the Stock Quote web service to collect the watch list data but it does this across the high speed Internet instead of the slow cellular network as illustrated below:

The custom Node.ACS service is shown below. Note that an additional feature in this Node.ACS service is that the Watch List symbols are retrieved from ACS Custom Object. This enables watch lists to be maintained across mobile devices.

var ACS = require('acs').ACS;
var logger = require('acs').logger;
var EventEmitter = require('events').EventEmitter;
var https = require('http');
var sessionID = null;
var stocks;
ACS.init('', ''); // use your ACS OAuth key and secret

function refreshPrice(req, res) {
    var uid = req.query.uid;
    var Event = new EventEmitter;
    var results = [],
        evt_count = 0;
    // SETUP EVENT LISTENER
    Event.on("HTTP_COMPLETE", function (e) {
        console.log("EVENT: HTTP_COMPLETE");
        evt_count++;
        console.log(evt_count);
        if (evt_count >= stocks.length) {
            console.log("close response, results = " + JSON.stringify(results));
            res.write(JSON.stringify(results));
            res.end();
        }
    });
    ACS.Objects.query({
        page: 1,
        per_page: 100,
        classname: "stocks",
        where: {
            user_id: uid,
        }
    }, function (data) {
        console.log(JSON.stringify(data));
        stocks = data.stocks;
        var l = stocks.length;
        if (l == 0) {
            Event.emit("HTTP_COMPLETE");
        };
        for (var i = 0; i < l; i++) {
            marketOnDemandQuote(stocks[i].symbol);
        }
    })

    function marketOnDemandQuote(symbol) {
        var myreq =
            https.get('http://dev.markitondemand.com/Api/Quote/json?symbol=' + symbol, function (r) {
            r.setEncoding('utf8');
            r.on('data', function (chunk) {
                console.log(chunk);
                var o = {}, d = JSON.parse(chunk);
                o.symbol = d.Data.Symbol;
                o.name = d.Data.Name;
                o.lastPrice = d.Data.LastPrice;
                o.change = d.Data.Change;
                o.changePercent = d.Data.ChangePercent;
                o.timestamp = d.Data.Timestamp;
                results.push(o);
                Event.emit("HTTP_COMPLETE");
            });
        });
    }
};
exports.refreshPrice = refreshPrice;
// Source code attribution: Asim Siddiqui and Bert Grantges

Conclusion

Appcelerator’s Node.ACS Platform as a Service can be used to build mobile optimized middleware services in Node.js. The middleware service reduces the overhead in retrieving the watch list data by making repeated calls to a stock quote web service and presents the aggregated data that the mobile application needs. This results in improved user experience and reduced latency and throughput requirements of the mobile application.

While this example was designed around a stock watch list, the principles can be applied to many other use cases such as sales flash reports, key performance indicator dashboards and other applications where the back end data is not optimized for the mobile application or when data needs to be mashed up from disparate back end data sources.

The Node.ACS online documentation is a good next step for learning about Appcelerator Custom Cloud Service and can be found here: http://docs.appcelerator.com/titanium/latest/#!/guide/Node.ACS


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!

Page 1 of 9012345...102030...Last »