Appcelerator Developer Blog

Building a custom front-end to ACS using Node.ACS [Part 1]

With Titanium you use Javascript to build native mobile Apps. With Node.ACS you now can use Javascript to write your back-end code, with super easy access to ACS database and storage, all hosted on our secure and scalable cloud infrastructure. As an added advantage, your local Node.ACS installation is a self-contained environment, that doesn’t require you to install a local web server for testing. As you will see later on, when you run a Node.ACS app, it is automatically listening for requests on a given HTTP Port; you just have to point your browser to it!

Getting started

Assuming you have Node and NPM, open up a terminal/command window and type:

$ sudo npm install -g acs

This will install Node.ACS globally on your computer. To start using it you need to login to your appcelerator account by typing:

$ acs login

Now that you have successfully logged in, you’re ready to create your first app. Change to the folder where you’d like your app to live, for example cd ~/Documents/MyApps and type:

$ acs new MyFirstApp

This command will create for you a new folder with the name of your new app. Now change to that folder (cd MyFirstApp) and you’ll see the files that were created for you. I’ll explain them later.

To run the app, simply type:

$ acs run

Your terminal/command window will show something like this:

When you run your app, Node.ACS is actually setting up a local server for you and at this point it is waiting for connections. As you can see in the screenshot above, ACS is listening on port 8080. This means that all you need to do is browse to that address. Launch up your web browser and point it to http://localhost:8080 and you’ll see this:

This HTML page is being served by your local Node.ACS server, but it’s much more than this. Node.ACS has a full-featured MVC framework based on ExpressJS. If you go to your application folder you’ll see that some files and folders were created for you.

These folders/files are explained in more detail in this page, so make sure you check it out. However, I’ll explain how to work with some of these files from a practical standpoint, and in the process we’ll create a complete website.

Building a Website

If you’re new to MVC this will probably take some time reading the code, testing and re-reading, but simply because of how MVC separates concerns. With an MVC framework, your pages(views) are static. When you want to make them dynamic, you pass static information to them. A templating engine then takes over to render the static page with new dynamic data. If you come from a background of developing websites using a “traditional” paradigm, MVC may feel weird at first. If you have worked with other MVC frameworks before, they you will feel right at home. In any case, MVC is arguably the best way of writing scalable applications.

If you go to your “Views” folder, you’ll see a file named “index.ejs”. Instead of an HTML extension, it is using EJS. The reason for this is that Node.ACS is using Embedded Javascript as its templating engine.

<!DOCTYPE html>
<html>
  <head>
     <title><%= title %></title>
    <link rel='stylesheet' href='/css/style.css' />
  </head>
  <body>
       <h2>Node.ACS</h2>
    <p><%= title %></p>
  </body>
</html>

Notice <%= title %> inside the Title Tag and the Body. This is the way you tell EJS to insert dynamic data into your template. Title in this case is a variable that was sent to the template before getting it rendered and sent to the browser. The benefit of using these templates is that you build your HTML as a static page, and use placeholders during your design process to represent dynamic data. When your page is ready to be implemented, you simply change the dynamic parts to use the corresponding variable name and save the file with .ejs extension. To show the page with dynamic data, you use the page controller, which you can find under controllers/application.js.

function index(req, res) {
     res.render('index', { title: 'Welcome to Node.ACS!' });
}

This function is receiving two objects: req and res. As their names imply, req has information about how the user got here (the request), and res holds information and provides methods to take the user some place else (the response).

In this example we’re using the “render” method of the res object. This method is receiving the name of the view, and an object with all the variables that you’d like to make available to your view, in this case title, and the static template gets rendered with this new data. If you change the value of title, you’ll see it changing on the browser. However your server is still running with a previous version of your files. You need to stop the server and restart it because that part of the Javascript function is already running and changes will not take effect until you run it again. This is as simple as going to your terminal, hitting CTRL+C to break the execution, and running “acs run” again; or simply pressing the “up” key on your keyboard which will type it for you.

We’re still missing one important detail. How do we tell the framework that the “main” page of your app will be handled by the index function that lives inside application.js? You configure these mapping (or route as they’re called) in config.json.

{
  "routes":
  [
    { "path": "/", "callback": "application#index" }
  ],
  "filters":
  [
        { "path": "/", "callback": "" }
  ],
  "websockets":
  [
       { "event": "", "callback": ""}
  ]
}

In this file we’re saying that when you browse to the home page, it will execute the function index inside application.js. We’ll see more about filters in the second part of this post, and websockets are explained here.

For simplicity, let’s create a trivial page that will be displayed when navigating to /newpage.

Step 1: Create your route by adding it to your config.json

[
    { "path": "/", "callback": "application#index" },
    { "path": "/newpage", "callback": "newpage#newpage" }
]

Step 2: Write the “newpage” function in newpage.js. I’m using a separate file for illustration purposes.

function newpage(req,res){
     res.render('newpage', { greeting: 'I am the new page' });
}

Step 3: Create the template called newpage and make sure it is using the new variable “greeting”.

<!DOCTYPE html>
<html>
  <head>
     <title><%= greeting %></title>
    <link rel='stylesheet' href='/css/style.css' />
  </head>
  <body>
       <h2>Node.ACS</h2>
    <p><%= greeting %></p>
  </body>
</html>

Restart your server and browse to your page. Then change the URL to http://localhost:8080/newpage and you’ll see the new page.

These are the basic principles for building websites using Node.ACS. To learn more about the EJS templating engine and how you can use loops, arrays and other fun Javascript features, go to http://embeddedjs.com/getting_started.html. To learn more about the “response” and “request” objects, you can go to http://expressjs.com/api.html#req.params.

If you want to publish your website for everyone to see, simply type

$ acs publish

Node.ACS will give you a public URL in return. The next time you publish, use the --force parameter to tell Node.ACS to overwrite your previous pages.

Final thoughts

This is a full-featured web MVC framework. You can use anything you’d normally use when developing websites, such as JQuery or Bootstrap. Just make sure that any library you use, or any dependency for that matter, is saved in the /public folder. From your views, the /public folder is the root folder, so if you placed an image at /public/image.png, from your view you would reference it like <img src=”/image.png” />

Stay tuned for the second part of this post, where we’ll apply this concepts to build a custom front-end to ACS.

Have fun!


3.1.1 Release Candidate of Titanium SDK/Studio Now Available

We’re pleased to announce the release candidate of an update to our 3.1.0 version of Titanium SDK/Studio. Version 3.1.1 brings hundreds of fixes and improvements across both products. Today, we’re asking you to help test out the release and provide feedback before it becomes generally available in early June.

Note: This is a pre-production release, and as such may contain regressions or other issues. Please do not use it in production, and keep backups of all important projects and data. If you find an issue, please report it in JIRA with a reproducible test case. We ask you provide feedback by Wednesday, 5/29.

How to Update

These are links to continuous integration builds. To install them, choose “Help Menu > Install Specific Titanium SDK…” from inside Titanium Studio.

To update Studio, please visit http://preview.appcelerator.com and follow the instructions to update to the RC stream, or to download a new install.

NPM Packages

Note: You may need to use ‘sudo’ before these terminal commands on OSX and Linux
npm install -g alloy@1.1.3-alpha
npm install -g titanium@3.1.1-alpha
To revert back to stable versions:
npm remove -g titanium
npm install -g titanium
npm remove -g alloy
npm install -g alloy

Updates in Titanium 3.1.1

Read the complete Release Notes. A full list of updates is available here.

Changes in supported OS versions

3.1.1 now has a minimum supported Android version of 2.3.3 (API level 10). The minimum iOS supported version is 5.x, which requires Xcode 4.3 or later.

API Changes

We’ve updated Titanium.Calendar, and deprecated Titanium.Android.Calendar.

Tooling updates

Support for Android r22 tooling. See Updating to Android r22 Tools for information about supporting older SDKs. Note that this beta still has some issues with r22 tooling on Windows, but this will be addressed in the final release.

Google Maps Support

We added a new userLocationButton property and updated the regionchanged event.

BlackBerry Support

We’ve folded in the latest version of our BlackBerry platform to this release. It’s no longer a separate download.


Updating to Android r22 Tools

Recently Google released an update (r22) to their Android developer tooling. This update has rearranged the directory structure of the tools and breaks the building of Android projects both from the CLI and inside Titanium Studio. Unless you need the updated functionality we recommend you hold off updating for now.

How do I know if I’ve run into this issue?

See TIMOB-13944. You’ll get a failure similar to “TypeError: argument of type ‘NoneType’ is not iterable”

How do I fix this problem?

There are a number of different ways to address the issue, depending on your goals:

If you want to use just the very latest version of the SDK, download the pre-release 3.1.1 build from http://builds.appcelerator.com.s3.amazonaws.com/index.html#3_1_X

If you need  to use prior versions of the SDK:


Featured Developer – ArtistBox

Today’s featured blog post comes from the creators of ArtistBox, Lucica Ibanescu and Titan Dan Tamas. ArtistBox is a sexy Titanium app that provides detailed information, news and music from your favorite artists. Learn more about their experience with Titanium below.


We’d like to share with you our story on how we built ArtistBox and to give you some insights on how we solved the (not a few) issues that we had.

What’s ArtistBox?

Artistbox is an iPhone application that finds the most complete information about your favourite artists: their biography, discography, news, concerts in your area and worldwide, videoclips, pictures and similar artists.

We strive to gather way more information than any other music discovery app on the market – for example by adding up-to-date news or hi-res pictures – and for the next versions we will add more cool features.

Why Titanium and why not native?

The app has two components: a client side – the app itself – and a server side. The whole app was build in five months by just two programmers @dan_tamas and @nosoloweb and we feel that coding it in objC wouldn’t have given us such an advantage from the time point of view.

There are many other reasons we chose Titanium:

  • depending on how the app sells we might want to go cross platform and build an Android version. In this case we will only have to work on the UI side of the app while anything else will remain untouched and working out of the box.
  • the fact that with a few lines of code we could have a working proof of concept was an amazing advantage over doing mockups and then implementing them in the code.
  • we are very proficient with Appcelerator but we don’t know objC so we used what we knew best
  • we bootstrapped this so the development cost was only in hours of work and not having to pay one or more objC programmers was a real boost.
  • we developed the server in NodeJS at the same time with the app. Developing both the app and the server side in Javascript instead of JS and objC helped us keep the focus on the building proccess.

 
 

What issues did you need to overcome

At this point we’d like to get a little more technical and explain how we managed to overcome the problems we had with the app.

One issue was the amount of the XHR calls we had to make. When the app opens it fetches all the artists in the device’s music library and also basic data for each of them. As you can see in the screenshot the application is very visual, we have a lot of images and each artis will have a lot of information:

Way too many XHR calls

Our main goal was to make a very responsive app and due to the amount of server calls we had to find a balance between the information sent from the server and the number of calls. So we decided to go with many calls that return a small amount of information. The overall time the user has to wait might be bigger in this case but the app doesn’t lock and the feedback received is really fast.

We hit a wall here because the ASIHttpRequest – the objC library Titanium uses on the native side – has a limit of 4 concurrent requests. The rest of the requests are put in a queue and executed when the previous calls finish.

What ASI does is perfectly correct, there is no point in overloading the network with too may concurrent requests but in our case the user would have had to wait for ALL the images from the previous windows to load in order to be able to receive the current window information.

We modified the XHR library to be able to handle a queue and priorities and we set the images to have the lowest priority while the artist information (JSON data) has the highest priority. At the JS level we limit the simultaneous requests for the images at only 3 so we always have a free slot on the native side for the data – higher priority requests are passed to ASI immediately.

Of course we take advantage of the caching that XHR does and we have a request to the server only once: the first time a new resources is requested or when the time to live expired. This way after the initial load the number of global requests decreases drastically.

Blocking the UI

The images are diplayed in tableViewRows and if we had put the source of the image directy in the imageView the UI would have locked until the image was loaded.

What we did was create the image **but without** the source property, download the image locally and save it then populate the source with the local file URL. This way the table will scroll normally and the pictures will be loaded one by one giving the user a way better experience.

Youtube clips

We have to display lots of videoclips from Youtube which can be done in two ways:

  1. open the clip in mobile Safari or the Youtube app. This meant making the user leave ArtistBox and it was not an acceptable option.
  2. use webviews to load the clip – not a good approach as we had to keep the memory footprint as low as possible.

We came with a different approach: each time the user taps on a clip the app makes a call to the mobile version of the Youtube site, finds the streaming link and opens a videoplayer with the source URL set to this streaming link.

The disadvantage is that the user will have to wait for an extra request to the Youtube servers but the overhead is not too big. The fact that he/she can see the videoclip right inside the app makes it worth it.

There were a few more aspects we had to take care of. The first one was to show very clearly that the videos are coming from Youtube so we designed the thumbnails with the big “Youtube” watermark. We also had to filter the results within the Youtube APIs to return only the videos allowed to run on mobile and also in the user’s country.

You can download the module from Github, it is MIT licensed.

We believe that the complexity of ArtistBox pushed the Titanium framework to the limits as we are using a large number of its APIs in our app (tableViews, videoPlayer, audioPlayer, lots of imageViews, scrollableViews, httpClient, localStorage, UI transtions, webviews, etc) and not always in a common way. But we also believe that Titanium was the right choice and it reached our expectations :)

There are also a few modules we used and we want to thank their creators:

- a modified version of XHR by Raul Riera
- TiNetworkHelpers by Ben Bahrenburg
- a modified version of TiMiniBrowser by Rafael Kellermann Streit

Enough talking, let’s see some action

ArtistBoxApp from ArtistBox App on Vimeo.

ArtistBoxApp from ArtistBox App on Vimeo.

Final words

ArtistBox is a very complex application that has to deal with a huge amount of information while also being memory leaks free. Making it stable and very fast were our main purposes because the users are very sensitive when it comes to huge loading times and repeated crashes. Being able to offer them so much info about their favourite artists while displaying the UI in an instant were two very challenging tasks that we hope we completed successfully. You can see we’re not trying to be modest here, test the app for yourselves and let us know what you think.


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!

Page 2 of 9212345...102030...Last »