Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 9 Local Data

Removing aPreference

There may be times when you need to remove an option from the Preferences store or even remove all options. If you want to remove your LastUsedBoardId preference, you can write

Preferences.Remove("LastUsedBoardId");

If you want to remove all options, you can write

Preferences.Clear();

Secure Storage

When building an application, there will quite often be an occasion where you need to store an API token or some form of data that needs to be held securely. .NET MAUI provides another API that makes sure that the values you supply are held securely on each of the platforms’ secure storage locations.

As always with a new API provided by .NET MAUI, you must register it with the MauiAppBuilder in your MauiProgram.cs file, so let’s open up that file and add the following line into the CreateMauiApp method:

builder.Services.AddSingleton(SecureStorage.Default);

This will allow you to declare a dependency on ISecureStorage in your class constructors and have it provided for you.

Storing a Value Securely

You don’t currently have a need to write a secure value just yet. It will follow in the next chapter, but to give a brief explanation of this type of local data, you can take a look at an example.

291

Chapter 9 Local Data

To save a value in secure storage with the key of apiToken and a value of 1234567890, you can write the following:

await SecureStorage.Default.SetAsync("apiToken", "1234567890");

Reading a Secure Value

It is also possible to retrieve the value you have stored securely by using the GetAsync method and passing in the key. It is worth noting that if the key does not exist, the method will return null.

To retrieve a value in secure storage with the key of apiToken, you can write the following:

string apiToken = await SecureStorage.Default. GetAsync("apiToken");

if (apiToken is not null)

{

}

Removing a Secure Value

As with Preferences, you can remove and remove all secure values. To remove a specific value, remove the key:

bool success = SecureStorage.Default.Remove("apiToken");

To remove all values, use the RemoveAll method:

SecureStorage.Default.RemoveAll();

292