Introduction:
Settings plugin makes it easier to create cross-platform .NET apps and have cross platform settings. Manage and use all settings from one PCL/NetStandard library and save natively on each platform. Also this plugin stores settings natively on each platform and does NOT save them to Json. This allows you to use native functionality such as SharedPreferences on Android and NSUserDefaults on iOS.
Requirements:
- This article source code is prepared by using Visual Studio Community for Mac (7.4). And it is better to install latest visual studio updates from here.
- This sample project is Xamarin.Forms PCL project and tested in Android emulator and iOS simulators.
- Used Settings Nuget Package version is V3.1.1.
Description:
This article can explain you below topics:
1. How to create Xamarin.Forms PCL project with Visual Studio for Mac?
2. How to store and read string values using Settings?
3. How to implement login/logout pages functionality using Settings?
3. How to implement login/logout pages functionality using Settings?
1. How to create Xamarin.Forms PCL project with Visual studio for Mac?
First we need to create the new Xamarin.Forms project.
- Launch Visual Studio for Mac.
- On the File menu, select New Solution.
- The New Project dialog appears. In the left pane Multiplatform > App > Xamarin.Forms > Blank Forms App and click on Next.
- Enter your App Name (Ex: AppSettingsSample). Select Target Platforms to Android & iOS and Shared Code to Portable Class Library after that click on Next button.
- You can choose your project location like below and Create new project.
And project structure will be.
- AppSettingsSample: It is for PCL shared code.
- AppSettingsSample.Droid: It is for Android.
- AppSettingsSample.iOS: It is for iOS.
2. How to store and read string values using Settings?
We need to follow below few steps to store user settings in Xamarin.Forms.
Step 1: Add Settings Nuget Package:
Right click on Packages folder => Add Packages.
After that Add Packages window will open, search for "Xam.Plugins.Settings" and click on Add Package to install it.
Now your PCL project should include above package like below:
Also please add above package to AppSettingsSample.Droid and AppSettingsSample.iOS projects by following same above steps like AppSettingsSample PCL project. And make sure same version Settings package should add to Android and iOS project Packages folder like below.
Step 2: Create a Helper Class that properties need to store:
Create Helpers folder in PCL, after that right click on Models folder => Add =>New File => General => Empty Class and name it UserSettings.
UserSettings.cs
Open UnserSettings class file and add below properties:- // Helpers/Settings.cs
- using Plugin.Settings;
- using Plugin.Settings.Abstractions;
- namespace AppSettingsSample.Helpers
- {
- /// <summary>
- /// This is the Settings static class that can be used in your Core solution or in any
- /// of your client applications. All settings are laid out the same exact way with getters
- /// and setters.
- /// </summary>
- public static class UserSettings
- {
- static ISettings AppSettings {
- get {
- return CrossSettings.Current;
- }
- }
- public static string UserName
- {
- get => AppSettings.GetValueOrDefault(nameof(UserName), string.Empty);
- set => AppSettings.AddOrUpdateValue(nameof(UserName), value);
- }
- public static string Password
- {
- get => AppSettings.GetValueOrDefault(nameof(Password), string.Empty);
- set => AppSettings.AddOrUpdateValue(nameof(Password), value);
- }
- public static string MobileNumber
- {
- get => AppSettings.GetValueOrDefault(nameof(MobileNumber), string.Empty);
- set => AppSettings.AddOrUpdateValue(nameof(MobileNumber), value);
- }
- public static void ClearAllData()
- {
- AppSettings.Clear();
- }
- }
- }
Above helper class will helpful to store/read string values(UserName, Password, MobileNumber). Also we added method to clear all user settings values.
This library uses the native settings management, which means all settings are persisted across app updates, saved natively, and can be integrated into native settings. - Android: SharedPreferences
- Apple: NSUserDefaults
- UWP: ApplicationDataContainer .
- NET: UserStore -> IsolcatedStorageFile
Since data is stored natively on each platform only certain data types are supported by Settings plugin:
- Boolean
- Int32
- Int64
- String
- Single(float)
- Double
- Decimal
- DateTime (Stored and retrieved in UTC).
3. How to implement login/logout pages functionality using Settings?
- After login success, app should not show the login page until logout from the app.
- If user logout from the application, app need to redirect to login page.
ViewModels:
It is best practices to write business logic in view models before start to build views user interface. Create ViewModels folder in PCL and add functionality for the view models below.
BasePageViewModel.cs
This view model will helpful to store/read string values(UserName, Password, MobileNumber).
- using System.ComponentModel;
- using System.Runtime.CompilerServices;
- using AppSettingsSample.Helpers;
- using Xamarin.Forms;
- namespace AppSettingsSample.ViewModels
- {
- public class BasePageViewModel : INotifyPropertyChanged {
- public INavigation _navigation;
- public string UserName
- {
- get => UserSettings.UserName;
- set{
- UserSettings.UserName = value;
- NotifyPropertyChanged("UserName");
- }
- }
- public string Password
- {
- get => UserSettings.Password;
- set {
- UserSettings.Password = value;
- NotifyPropertyChanged("Password");
- }
- }
- public string MobileNumber
- {
- get => UserSettings.MobileNumber;
- set {
- UserSettings.MobileNumber = value;
- NotifyPropertyChanged("MobileNumber");
- }
- }
- #region INotifyPropertyChanged
- public event PropertyChangedEventHandler PropertyChanged;
- protected void NotifyPropertyChanged([CallerMemberName] string propertyName = ""){
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- #endregion
- }
- }
This view model will helpful to store string values (UserName, Password, MobileNumber) also for user login.
- using System.Threading.Tasks;
- using System.Windows.Input;
- using AppSettingsSample.Views;
- using Xamarin.Forms;
- namespace AppSettingsSample.ViewModels
- {
- public class LoginPageViewModel : BasePageViewModel {
- public ICommand LoginCommand { get; private set; }
- public LoginPageViewModel(INavigation navigation){
- _navigation = navigation;
- LoginCommand = new Command(() => UpdateUserInfo());
- }
- void UpdateUserInfo() {
- _navigation.PushAsync(new HomePage());
- }
- }
- }
This view model will helpful to read string values (UserName, Password, MobileNumber) also for user logout.
- using System.Threading.Tasks;
- using System.Windows.Input;
- using AppSettingsSample.Helpers;
- using AppSettingsSample.Views;
- using Xamarin.Forms;
- namespace AppSettingsSample.ViewModels
- {
- public class HomePageViewModel: BasePageViewModel {
- public ICommand LogoutCommand { get; private set; }
- public HomePageViewModel(INavigation navigation) {
- _navigation = navigation;
- LogoutCommand = new Command(() => ResetUserInfo());
- }
- void ResetUserInfo()
- {
- _navigation.PushAsync(new LoginPage());
- UserSettings.ClearAllData();
- }
- }
- }
Views:
Create Views folder in PCL and add below xaml content pages.
LoginPage.xaml
This page is for User Login UI.
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- BackgroundColor="#D5E7FA" x:Class="AppSettingsSample.Views.LoginPage">
- <StackLayout Spacing="20" Margin="10" VerticalOptions="Center">
- <Entry Placeholder="User Name" Text="{Binding UserName}" HeightRequest="40" HorizontalOptions="FillAndExpand" TextColor="Gray" BackgroundColor="White"/>
- <Entry Placeholder="Password" Text="{Binding Password}" IsPassword="true" HeightRequest="40" HorizontalOptions="FillAndExpand" TextColor="Gray" BackgroundColor="White"/>
- <Entry Placeholder="Mobile Number" Keyboard="Telephone" Text="{Binding MobileNumber}" HeightRequest="40" HorizontalOptions="FillAndExpand" TextColor="Gray" BackgroundColor="White"/>
- <Button Text="Login" HorizontalOptions="FillAndExpand" TextColor="Blue" Command="{Binding LoginCommand}" HeightRequest="40" BackgroundColor="White"/>
- </StackLayout>
- </ContentPage>
- using System;
- using System.Collections.Generic;
- using AppSettingsSample.ViewModels;
- using Xamarin.Forms;
- namespace AppSettingsSample.Views
- {
- public partial class LoginPage : ContentPage
- {
- public LoginPage()
- {
- InitializeComponent();
- BindingContext = new LoginPageViewModel(Navigation);
- }
- }
- }
This page is for User Logout UI.
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- BackgroundColor="#D5E7FA" x:Class="AppSettingsSample.Views.HomePage">
- <StackLayout Padding="40,60,40,0" Spacing="30">
- <Label Text="User Details" TextColor="Blue" HorizontalOptions="CenterAndExpand" FontSize="30"/>
- <StackLayout Spacing="10">
- <Label Text="UserName:" Font="20" TextColor="Black" HorizontalOptions="FillAndExpand"/>
- <Label Text="{Binding UserName}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>
- <Label Text="Mobile Number:" Font="20" HorizontalOptions="FillAndExpand" TextColor="Black"/>
- <Label Text="{Binding MobileNumber}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>
- <Button Text="Logout" HorizontalOptions="FillAndExpand" TextColor="Blue" Command="{Binding LogoutCommand}" HeightRequest="40" BackgroundColor="White"/>
- </StackLayout>
- </StackLayout>
- </ContentPage>
- using System;
- using System.Collections.Generic;
- using AppSettingsSample.ViewModels;
- using Xamarin.Forms;
- namespace AppSettingsSample.Views
- {
- public partial class HomePage : ContentPage
- {
- public HomePage()
- {
- InitializeComponent();
- BindingContext = new HomePageViewModel(Navigation);
- }
- }
- }
Demo screens from Android:
Demo screens from iOS:
You can also directly work on below sample source code to understand this article.
FeedBack Note: Please share your thoughts, what you think about this post, Is this post really helpful for you? I always welcome if you drop comments on this post and it would be impressive.
What a nice and well redacted post man, thank you very much!!!
ReplyDeleteSir Can I do with web services?
ReplyDeletethanks you. it is well written tutorial
ReplyDeletehey guy !! i'm very happy to read your tutorials. you are ammazing. But i have a big problem with this section. How to use this library in my project ?? i use already a class on my properties. can you help me please ??
ReplyDelete