How can I save some user data locally on my Xamarin Forms app?

蓝咒 提交于 2019-11-29 20:09:04

You have a couple options.

  1. SQLite. This option is cross-platform and works well if you have a lot of data. You get the added bonus of transaction support and async support as well. EDIT: In the past I suggested using SQLite.Net-PCL. Due to issues involving Android 7.0 support (and an apparent sunsetting of support) I now recommend making use of the project that was originally forked from: sqlite-net
  2. Local storage. There's a great nuget that supports cross-platform storage. For more information see PCLStorage
  3. There's also Application.Current.Properties implemented in Xamarin.Forms that allow simple Key-Value pairs of data.

I think you'll have to investigate and find out which route serves your needs best.

As far as security, that depends on where you put your data on each device. Android stores app data in a secure app folder by default (not all that secure if you're rooted). iOS has several different folders for data storage based on different needs. Read more here: iOS Data Storage

Another option is xamarin forms settings plugin https://github.com/jamesmontemagno/SettingsPlugin. If u need store e.g. user instance, just serialize it to json when storing and deserialize it when reading.

Uses the native settings management

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

      public User CurrentUser
      {
         get
         {
            User user = null;
            var serializedUser = CrossSettings.Current.GetValueOrDefault<string>(UserKey);
            if (serializedUser != null)
            {
               user = JsonConvert.DeserializeObject<User>(serializedUser);
            }
    
            return user;
         }
         set
         {
            CrossSettings.Current.AddOrUpdateValue(UserKey, JsonConvert.SerializeObject(value));
         }
      }
    
chunhunghan

Please use Xamarin.Essentials

The Preferences class helps to store application preferences in a key/value store.

To save a value:

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

To get a value:

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