2

Need to detect existence of a file in the app's Documents folder (data.json) using javascript in index.html file. The JS code can test existence of files in the folder where the index.html file resides. The html+JS file works if I hardcode the url to the Documents folder, but for the deploying to a device I'd like to programmatically find the file.

Can I do this in JS (embedded in the index.html file)? If that is not allowed, do I need to compose the javascript in ObjectiveC and then load the html + the string containing JS code that uses "src=file:/%@/data.json",stringRelativePathToDocumentsVar as alluded to in this SO question by @fallenreaper.

Below is JavaScript code in my index.html file:

<script type='text/javascript'>
    function get_error(x){
        document.getElementsByTagName('span')[0].innerHTML+=x+" does not exist.";
        }
    url="~/Documents/data.json";
    url+="?"+new Date().getTime()+Math.floor(Math.random()*1000000);
    var el=document.createElement('script');
    el.id="data.json";
    el.onerror=function(){if(el.onerror)get_error(this.id)}
    el.src=url;
    document.body.appendChild(el);
</script>

The code needing forming in ObjC would look like this:

NSString *urlRelPath = [[@"<script type=\"text/javascript\" url=\"file:/%@" stringByAppendingString:documents_path] stringByAppendingString:@"\"></script>"];

Where documents_path is obtained using (from this SO Q:):

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents_path = [paths objectAtIndex:0];

Let me know if this on the right track, or if I should consider something more elegant. Any hints/tips will be appreciated.

** Update ** The file data.json can be any file (txt,xml,etc) where I store a dictionary passed to this app via URL scheme. Technically, this app runs locally with out network access. This app (appA) queries another app installed on the device (appB), which sends data to appA. AppA then saves the information locally and I need to display a notification that the file is available (or updated).

Community
  • 1
  • 1
sAguinaga
  • 638
  • 13
  • 31
  • How will the index.html be viewed—in Mobile Safari or an embedded UIWebView? – neilco Jan 02 '14 at 11:13
  • Good Q:, right now for prototyping purposes in UIWebView, but I just realized, that instead of saving the `data.json` file in the `~/Documents` directory, I should save it to the directory where the `html` files are, this way JS can find it. – sAguinaga Jan 02 '14 at 11:24
  • The data.json is better served from the web server so that you don't encounter any sandboxing issues trying to access the app's Document folder from Mobile Safari. – neilco Jan 02 '14 at 11:30

1 Answers1

0

In my Cordova application I download files for my app and save them in the Documents folder. I then link to these images, videos, and audio relatively using

"../../Documents/myfile/myfile.jpg"
Playforward
  • 560
  • 2
  • 6
  • 21