Created
December 17, 2014 12:44
-
-
Save caspahouzer/a4d0f0093a9110ac8913 to your computer and use it in GitHub Desktop.
download file and save to private ios directory
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
function getFileAndSave (filename, url) { | |
var file_obj = { | |
file: filename, | |
url: url, | |
path: null | |
}; | |
var testFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory); | |
var privateDocFolder = testFile.nativePath.replace('Documents/', ''); | |
privateDocFolder += 'Library/Private%20Documents/'; | |
if (Ti.Platform.getOsname() === 'android') { | |
if (Ti.Filesystem.isExternalStoragePresent()) { | |
privateDocFolder = Ti.Filesystem.externalStorageDirectory; | |
} else { | |
privateDocFolder = Ti.Filesystem.applicationDataDirectory | |
} | |
var nomediafile = Ti.Filesystem.getFile(privateDocFolder, '.nomedia'); | |
if (!nomediafile.exists()) { | |
nomediafile.write(' '); | |
} | |
} | |
var cacheBuster = new Date(); | |
var file = Ti.Filesystem.getFile(privateDocFolder, filename); | |
var localFile = Ti.Filesystem.getFile(privateDocFolder + '/' + url); | |
var cacheString = ''; | |
if (Ti.Platform.osname !== 'android') { | |
cacheString += '?cacheBuster=' + cacheBuster.getTime(); | |
} | |
if (file.exists()) { | |
file_obj.path = privateDocFolder; | |
return file_obj.path + '/' + filename + cacheString; | |
} else if (localFile.exists()) { | |
return privateDocFolder + '/' + url + cacheString; | |
} else { | |
if (Ti.Network.online) { | |
if (Ti.Network.networkType == Ti.Network.NETWORK_WIFI) { | |
var c = Ti.Network.createHTTPClient(); | |
c.setTimeout(10000); | |
c.onload = function () { | |
if (c.status == 200) { | |
var dir = privateDocFolder; | |
var folder = Ti.Filesystem.getFile(dir); | |
if (!folder.exists()) { | |
folder.createDirectory(); | |
} | |
var f = Ti.Filesystem.getFile(dir, filename); | |
f.write(this.responseData); | |
file_obj.path = dir + Ti.Filesystem.separator; | |
} else { | |
file_obj.error = 'file not found'; // to set some errors codes | |
} | |
}; | |
c.ondatastream = function () { | |
//if (fn_progress) fn_progress(e.progress); | |
}; | |
c.error = function (e) { | |
file_obj.error = e.error; | |
}; | |
c.open('GET', url); | |
c.send(); | |
} | |
} else { | |
file_obj.url = ''; | |
file_obj.error = 'no internet'; | |
} | |
return file_obj.url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment