Talk With Angel Garcia!

Talk With Angel Garcia!

a blog about software and beers

Xamarin Forms: App Settings vs User Preferences vs Secrets.

In our mobile apps we should handle configuration values in the correct way depending on the type of the value, let’s see the difference between them and how to manage each type in Xamarin Forms.

App Settings.

This is where we store the app configuration values such as endpoints, client ids, error codes and default values.

These values are often constants in our app, so we could change them only in our pre-build scripts as part of the CI/CD pipeline.

User Preferences.

Mobile apps will often require storing data that is specific to the current user, this is what we call user preferences, we need them to specify, for example, the app theme (Dark or Light), the user’s token or any value that represents the user’s preferred configurations.

These values need to be stored and available per user’s session in our apps, we need to keep them as long as the user is logged in.

Let’s see how to do it with the Preferences API (from Xamarin Essentials) that enables you to store application preferences as key/value.

To get started with Xamarin.Essentials you need to install the NuGet package in your projects, then initialize Xamarin Essentials by putting this in your MainActivity on the Android project:

Now we can use the Preferences API for store and retrieve values like this:


When we need to specify values that we don’t want to expose in the source code of our apps we use secrets, for example, your App Center apps secrets (😏 I know you have them in the code).

There are many ways to handle secrets, in Xamarin we have the awesome package called Mobile.BuildTools which help us by transforming a JSON file (ignored by the source code) to a Helper class with the secret values as statics so we can reference them as we need in the code.

First thing you need is to install Mobile.BuildTools in your projects, then add a JSON file in the root of your shared project called secrets.json and make sure to ignore it from your source control, the content of the JSON should be “SecretKey”: “SecretValue” as the following:

Once you build the app a new file (Secrets.cs) is created for you using those secrets under the Helpers namespace and folder (should be ignored too):

Then we could use the secrets, for example, to initialize App Center:

😉 Now you know how to handle configuration values no matter the type, happy coding!



Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.