Search code examples
c#windows-8windows-phone-8

How are normal people supposed to persist settings in a Windows Phone 8 app?


I'm in the process of writing a Windows Phone 8 app, so I can capture that much sought-after 3% market share, and am having a hard time persisting user settings within the application.

I first ran across this blog which goes over the basics of the Windows.Storage namespace, which is intended to do exactly this sort of thing. Yay!

However, I guess the author never actually ran his own code, as otherwise he would know that the second you call ApplicationData.Current.LocalSettings, you'd get a NotImplementedException exception. To the MSDNs we go!

Well, this makes it pretty clear that this API is not implemented on Windows Phone 8. I came to this conclusion when it said, "This API is not implemented and will throw an exception if called." - Well that's great.

So, maybe there's some other similar APIs. After a bit more Googling, I came across this blog. It's called "Windows 8 Apps - Must Know Tricks!". This looks official! It goes over all sorts of really cool looking persistence APIs, including permanent and transient storage, roaming storage, etc.

But guess what: RoamingFolder, RoamingSettings, TemporaryFolder, LocalSettings - None of it is implemented on Windows Phone 8.

Did implementing these somewhat-key features just slip their mind? Am I supposed to create a local SQL database to store basic app settings, or is there something simple I'm not finding?


Solution

  • Ah ha! Figured this out. I dug up the Windows Phone 7 API docs, and the legacy APIs actually still work on Windows Phone 8 as well.

    public static void Session_PersistSession(string ticket)
    {
       if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionTicket"))
       {
          IsolatedStorageSettings.ApplicationSettings["SessionTicket"] = ticket;
       }
       else
       {
          IsolatedStorageSettings.ApplicationSettings.Add("SessionTicket", ticket);
       }
    
       IsolatedStorageSettings.ApplicationSettings.Save();
    }
    
    public static string Session_LoadSession()
    {
       string ticket;
       if (IsolatedStorageSettings.ApplicationSettings.TryGetValue<String>("SessionTicket", out ticket))
       {
          return ticket;
       }
    
       return null;
    }