Shared Preferences in Xamarin.forms

北慕城南 提交于 2019-12-25 18:37:03

问题


I have tried to save login value as true if user has logged in once by using

Application.Current.Properties["isLoggedIn"] = "true";

but its not working. If i remove my app from background it again shows the login page but if user is logged in it should show the next page.


回答1:


When using 'Application Properties Dictionary' you have to keep in mind few things:

  • According to the official documentation: 'The Properties dictionary is saved to the device automatically'. However, if you want to ensure persistence you have to explicitly call SavePropertiesAsync().
  • The Properties dictionary can only serialize primitive types for storage. Attempting to store other types such as List can fail silently.

Read the official documentation carefully and pay attention to details.

Here is a code example:

private async Task SaveApplicationProperty<T>(string key, T value)
{
    Xamarin.Forms.Application.Current.Properties[key] = value;
    await Xamarin.Forms.Application.Current.SavePropertiesAsync();
}

private T LoadApplicationProperty<T>(string key)
{
    return (T) Xamarin.Forms.Application.Current.Properties[key];
}

// To save your property
await SaveApplicationProperty("isLoggedIn", true);

// To load your property
bool isLoggedIn = LoadApplicationProperty<bool>("isLoggedIn");

Base on your needs you may consider Local Database or Settings Plugin instead. However for saving just a few primitive values Application Properties approach should be good enough.




回答2:


Xamarin Forms now includes Xamarin Forms Essentials and contains the Preferences component that you need. Check out the official website and try it. https://docs.microsoft.com/en-us/xamarin/essentials/preferences?tabs=ios

This is an example of how to manage preferences with Essentials.

  • To save a value for a given key in preferences:

    Preferences.Set("my_key", "my_value");

  • To retrieve a value from preferences or a default if not set:

    var myValue = Preferences.Get("my_key", "default_value");

  • To remove the key from preferences:

    Preferences.Remove("my_key");

  • To remove all preferences:

    Preferences.Clear();

Supported Data Types:

  • bool

  • double

  • int

  • float

  • long

  • string

  • DateTime



来源:https://stackoverflow.com/questions/43499477/shared-preferences-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!