Search code examples
javascriptwindows-phone-8.1winjsuwp

What is the recommended way to persist the data in background task? [UWP/W/WP apps]


The question is quite simple, but I seriously couldn't find any sample that would demonstrate something I'm trying to achieve, maybe it's me who is didn't get the concept of background tasks in uwp applications (or windows / windows phone 8).

I'm creating an application that is polling some data (traffic incidents) and would like to be able to notify the user about the closes ones even if he is not using the application. So I reckon I would use the background task. (I hope I get that part right).

So in the background task, which I've set to run on timer of 15 minutes, under the condition of "InternetAvailable", I fetch the data asynchronously and once it's done, I'm completing the deferral object as it's required. All works ok.

The question is, what object shall I use in order to persist the data so I could read the data once the application is opened?

I've tried the WinJS.Application.sessionState but that gets lost once the application is ready (opened).

I've tried the Windows.Storage.ApplicationData.current.localSettings but it says there is a type mismatch, apparently I'm trying to put in there the object, if String is expected (I reckon)...

So does anyone know what is the best practice here ?

Thank you


Solution

  • You have full acess to the WinRT API, so you can write a file (and read the same file once the application is opened):

    function saveData(dataObj) {
        var applicationData = Windows.Storage.ApplicationData.current;
        var localFolder = applicationData.localFolder;
        return localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (sampleFile) {
                return Windows.Storage.FileIO.writeTextAsync(sampleFile, JSON.stringify(dataObj));
        });
    }