Xamarin Forms Sharedpreferences cross

user1845593 picture user1845593 · Aug 28, 2015 · Viewed 10k times · Source

I'd like to know what is the best solution to manipulate application settings in a cross-platform way.

In iOS we can change the settings outside the app in the settings screen, but we don't have that in windows phone and android.

So, my idea is to create a normal page/screen inside the app that shows all my application settings and have an interface with Save() and Get() methods that I can implement specific per device using DependencyServices.

Is this the right way to do it?

Answer

Daniel Luberda picture Daniel Luberda · Aug 28, 2015
  1. The Application subclass has a static Properties dictionary which can be used to store data. This can be accessed from anywhere in your Xamarin.Forms code using Application.Current.Properties.
Application.Current.Properties ["id"] = someClass.ID;

if (Application.Current.Properties.ContainsKey("id"))
{
    var id = Application.Current.Properties ["id"] as int;
    // do something with id
}

The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted. Xamarin.Forms 1.4 introduced an additional method on the Application class - SavePropertiesAsync() - which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.

https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/app-lifecycle/

  1. Xamarin.Forms plugin which uses the native settings management.

    • Android: SharedPreferences
    • iOS: NSUserDefaults
    • Windows Phone: IsolatedStorageSettings
    • Windows Store / Windows Phone RT: ApplicationDataContainer

https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Settings