dimanche 28 juin 2015

How to schedule data sync in PhoneGap app, retrieving JSON

I am building a PhoneGap app, and currently have setup some datasources that have a JSON feed I pull from, to populate my app with data. Right now, it only pulls that data once, the first time the app is run.

I would like to download data everytime the app first opens, and then if it stays open for longer than 15 minutes, it updates again. The json feed can be queried with a last_mod_day in the URL so it pulls only the data that has changed.

What would be recommended to go about this, and how to check for a WiFi/Data Connection on the phone, and if not it fails quietly?

Below is the code for my current function to grab the feed.

function downloadFileError(evt) {
console.log('downloadFileError: ');
console.log(evt.target.error);
}

function downloadFile(ep) {
window.requestFileSystem(
    LocalFileSystem.PERSISTENT, 
    0, 
    function onFileSystemSuccess(fileSystem) {
        fileSystem.root.getFile("dummy.json", {
            create: true,
            exclusive: false
        }, 
        function gotFileEntry(fileEntry) {
            var filename = cordova.file.dataDirectory + 'assets/json/' + ep + '.json';
            var fileTransfer = new FileTransfer();
            fileEntry.remove();
            console.log('looking at ' + filename);
            fileTransfer.download(
                encodeURI("http://ift.tt/1GTLmzu" + ep), 
                filename,
                    function(theFile) {
                        console.log("download complete: " + theFile.toURL());
                    }, 
                    function(error) {
                        console.log("DLERR: src=" + error.source + " t=" + error.target);
                    }
            );
        }, 
        function(evt) {
            console.log(evt);
            console.log('fn: ' + filename);
        }
        );
    }, 
downloadFileError);
}

function downloadDynamicPages() {

var deferred = $.Deferred();

var pages = ['setOne','setTwo','setThree','setFour','setFive','setSix'];
var cnt = 0;
var total_pages = pages.length; 

//checkConnection();

$.each(pages,function(k,v) {

    console.log('looking at ' + v);
    downloadFile(v);
    cnt++;
    if(cnt >= total_pages) {
        deferred.resolve('all done with files');
    }
});


return deferred.promise();

}

Any help on any part of these questions would help me greatly. If needed, I can answer any questions. Thank you Stack.

Aucun commentaire:

Enregistrer un commentaire