Thursday, November 28, 2013

Caching Remote Images in Titanium Mobile

Previously, I demonstrated how to use Universal Image Loader for caching remote images on an android application. For Titanium Mobile Applications, I will show a method to achieve the same effect. Please note however that you may need to modify the code to handle the cleanup of any unused downloaded files.

Here is the code for the caching method:
1:  function cacheImageAndLoad(url, imageView){  
2:       var fileName = url.substring(url.lastIndexOf('/') + 1);  
3:       var fileCopy = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, fileName);  
4:       if (!fileCopy.exists()) {  
5:            var xhr = Ti.Network.createHTTPClient({  
6:                 onload : function(e) {  
7:                      fileCopy.write(xhr.responseData);  
8:                      imageView.image = fileCopy.nativePath;  
9:                 },  
10:                 onerror : function(e) {  
11:                      /*  
12:                       * show default image  
13:                       */  
14:                 },  
15:                 timeout : 20000  
16:            });  
17:            xhr.open('GET', url);  
18:            xhr.send();  
19:       }  
20:       else {  
21:            imageView.image = fileCopy.nativePath;  
22:       }  
23:  }  

Check the demo application code here

No comments:

Post a Comment