Created
September 24, 2013 08:10
-
-
Save lele85/6681755 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var os_type = Titanium.Platform.getOsname() == 'android'?'android':'ios'; | |
var xhr = Titanium.Network.createHTTPClient(); | |
var getNotCached = function(url){ | |
var timestamp = new Date().getTime(); | |
if (url.indexOf('?') == -1) { | |
return url + '?nocache=' + timestamp ; | |
} | |
return url + '&nocache=' + timestamp ; | |
} | |
var getData = function(url,cbs){ | |
Ti.API.debug(url); | |
xhr.open("GET", url); | |
xhr.setTimeout(300000); | |
xhr.onload = function() { | |
cbs.success(xhr.responseData); | |
}; | |
xhr.ondatastream = cbs.progress; | |
xhr.onerror = cbs.error; | |
xhr.send(); | |
} | |
var getText = function(url,cbs){ | |
Ti.API.debug(url); | |
xhr.open("GET", url); | |
xhr.setTimeout(300000); | |
xhr.onload = function() { | |
cbs.success(xhr.responseText); | |
}; | |
xhr.onerror = cbs.error; | |
xhr.send(); | |
} | |
var getFileIos = function(url,dest, cbs){ | |
url = getNotCached(url); | |
var progress = cbs.progress || function(){}; | |
xhr.open("GET", url); | |
xhr.setTimeout(300000); | |
xhr.file = Ti.Filesystem.getFile(dest); | |
xhr.onload = cbs.success; | |
xhr.onerror = cbs.error; | |
xhr.ondatastream = cbs.progress; | |
xhr.send(); | |
}; | |
var getFileAndroid = function(url,dest, cbs){ | |
url = getNotCached(url); | |
var progress = cbs.progress || function(){}; | |
getData(url,{ | |
success : function(data){ | |
var destFile = Ti.Filesystem.getFile(dest); | |
if (data.type == 1) { | |
//Big files: http://developer.appcelerator.com/question/35041/large-file-download-on-mobile | |
Ti.API.info("[HTTP CLIENT] - Big File: " + url); | |
var downloadedFile = Ti.Filesystem.getFile(data.nativePath); | |
if (destFile.exists){ | |
destFile.deleteFile(); | |
downloadedFile.move(destFile.nativePath); | |
} | |
} else{ | |
//Small files | |
Ti.API.info("[HTTP CLIENT] - Small File: " + url); | |
destFile.write(data.responseData); | |
} | |
cbs.success(destFile); | |
}, | |
error : function(){ | |
cbs.error(); | |
}, | |
progress : progress | |
}); | |
}; | |
var platformGetFile ={ | |
'android' : getFileAndroid, | |
'ios' : getFileIos | |
} | |
exports.get = getText; | |
exports.getFile = platformGetFile[os_type]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment