Skip to content

Instantly share code, notes, and snippets.

@tripitakit
Last active December 29, 2015 03:09
Show Gist options
  • Save tripitakit/7605941 to your computer and use it in GitHub Desktop.
Save tripitakit/7605941 to your computer and use it in GitHub Desktop.
recursive double download example
var button1 = Ti.UI.createButton({
top:"10%",
title: "Get Files"
});
$.index.add(button1);
button1.addEventListener('click', getfiles);
function getfiles(){
Ti.API.info('get files was pushed');
var url_home ="http:";
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
var data1 = JSON.parse(this.responseText);
Ti.API.info('json count = ' + data1.length);
var image_url = "http://";
// start recursion with index 0
recursiveDownload(0);
function recursiveDownload(x) {
if (x < data1.lenght) {
Ti.API.info('x= ' + x);
var ht = data1[x].jth;
var hti = data1[x].jthi;
var ot = data1[x].jto;
var oti = data1[x].jtoi;
Ti.API.info ('data stream start');
Ti.API.info('x = ' + x );
Ti.API.info('ht = ' + ht);
Ti.API.info('hti = ' + hti);
Ti.API.info('ot = ' + ot);
Ti.API.info('oti = ' + oti);
// start with the download of hti
var htic = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hti);
if (htic.exists()) {
Ti.API.info(hti + ' exists on the phone');
// process otic
getOtic()
} else {
// dwonload and save htic
Ti.API.info(hti+ ' does not exists on phone');
var getimage = Titanium.Network.createHTTPClient();
getimage.setTimeout(10000);
getimage.onload = function() {
htic.write(this.responseData);
Ti.API.info('file hit '+hti+' saved')
// process otic
getOtic();
};
getimage.onerror = function(e) {
Ti.API.debug(hti, "Error: " + e);
getOtic();
};
getimage.open("GET", image_url+hti);
getimage.send();
}
function getOtic() {
Ti.API.info('oti check loop');
var otic = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, oti);
if (otic.exists()) {
Ti.API.info(oti + ' exists on phone');
Ti.API.info('check1');
// increment index and call recursion
recursiveDownload(x++);
} else {
Ti.API.info(oti + ' does not exist on phone line 65');
var getimage1 = Titanium.Network.createHTTPClient();
getimage1.setTimeout(10000);
getimage1.onload = function() {
otic.write(this.responseData);
Ti.API.info('file oti '+oti+' saved');
// increment index and call recursion
recursiveDownload(x++)
};
getimage1.onerror = function(e) {
Ti.API.debug(oti, "Error: " + e);
recursiveDownload(x++);
};
getimage1.open("GET", image_url+oti);
getimage1.send();
}
}
} else {
// data1 has been processed ...
};
};
}
xhr.open("GET", url_home);
xhr.send();
};
$.index.open();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment