Tuesday, April 10, 2012

Titanium for Android and RoR

Lately, I've been playing around with the Titanium IDE for mobile development.
Its pretty nice once you get a hang of it.
My first application (code name Moris) I made to communicate as a mobile front end for the Gizmo server.

It came out rather simple since my API on the server side are aleady set to spit out JSON structures.



I've found that the simplest way is as following:
First I created a generic send function with a global client object:



var SERVER = 'https://YOUR-DOMAIN/api/';


var send = function (action, data, resFunc){
client.open("POST", SERVER+action);
  if (resFunc!=null) {
  client.setOnload(resFunc);
  };
  client.send(data);
}


var client = Ti.Network.createHTTPClient({
     onload : function(e) {
         alert('success '+this.responseText);
     },
     onerror : function(e) {
         alert('error');
     },
     timeout : 5000  /* in milliseconds */
 });


Then I add a specific function for each API I'd like to call on the server:


exports.login = function(user,pwd) {
send("login", {mail:user, password:pwd}, function(e) {
         //alert(this.responseData);
        Ti.App.fireEvent("gizmo_login_complete", JSON.parse(this.responseText));
     });
};


exports.userInfo = function(resultFunction) {
send("user_info", {data:null}, resultFunction);
};


In these two examples, I've Pass a function that would handle the particular case of returned data.
For the login, I fire a Titanium event that is caught on the app.js while for the user info I inject the function each I do the call.




No comments:

Post a Comment

Please do not post spam on this blog, Spam sites will be reported to google.
thank you kindly.