如何为移动应用制作本地存储存储文件

时间:2019-01-25 13:53:04

标签: xml file xamarin.forms local-storage cross-platform

我正在构建一个Xamarin CrossPlatform应用程序,其所有数据库都在云API中, 但是我想在移动设备上创建一个本地存储文件,以便在有人登录时存储所有登录凭据。

请帮助我!

1 个答案:

答案 0 :(得分:1)

如果只想保存登录凭据,则应使用Xamarin.Essentials Storage

首先,将Xamarin.Essentials NuGet package添加到每个项目。

在Android中

protected override void OnCreate(Bundle savedInstanceState) {
    //...
    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code
    //...

要在Android上处理运行时权限,Xamarin.Essentials必须接收任何OnRequestPermissionsResult。将以下代码添加到所有Activity类:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

然后保存:

try
{
  await SecureStorage.SetAsync("loginCredential", "loginCredentialValue");
}
catch (Exception ex)
{
  // Possible that device doesn't support secure storage on device.
}

要检索:

try
{
  var loginCredential = await SecureStorage.GetAsync("loginCredential");
}
catch (Exception ex)
{
  // Possible that device doesn't support secure storage on device.
}