Saturday 12 May 2018

App settings in Xamarin.Forms

Introduction

This article will explain us how to saves specific properties directly to each platforms native settings APIs (NSUserDefaults, SharedPreferences, etc) using Xam.Plugins.Settings plugin in Xamarin.Forms. This plugin ensures the fastest, most secure, and reliable creation and editing settings per application. Additionally, it works with any Xamarin application, not just Xamarin.Forms. 


Requirements:
  • This article's source code is prepared by using Visual Studio. And it is better to install the latest Visual Studio updates from here.
  • This article is prepared on a MAC machine.
  • This sample project is Xamarin.Forms PCL project.
  • This sample app is targeted for Android, iOS. And, tested for Android & iOS.
Description:
Let's start

Step 1:
First, follow the below steps to create the new Xamarin.Forms project.
  • Open Visual Studio for Mac.
  • Click on the File menu, and select New Solution.
  • In the left pane of the dialog, let's select the type of templates to display. Multiplatform > App > Xamarin.Forms > Blank Forms App and click on Next.
  • Next Enter your app name (Ex: AppSettingsDemo). At the bottom select target platforms to Android & iOS and shared code to Portable Class Library and click on Next button.
  • Then choose project location with the help of Browse button and click on create.
Now project structure will be created like below.

  • AppSettingsDemo: It  is for shared code.
  • AppSettingsDemo.Droid: It is for Android.
  • AppSettingsDemo.iOS: It  is for iOS.

Step 2:
Now we need to add Xam.Plugins.Settings plugin on all platforms through NuGet.
Right, click on Packages-->AddPackages
Now, Search plugin with Xam.Plugins.Settings name like below.


Step 3:
After adding  Xam.Plugins.Settings automatically it will create Helpers folder with Settings.cs class and changed the name into UserSettings and we need to declare what ever properties we want to save in App Settings. Below class added 4 fields like UserName, MobileNumber, Email, Password.

UserSettings.cs

  1. // Helpers/Settings.cs  
  2. using Plugin.Settings;  
  3. using Plugin.Settings.Abstractions;  
  4.   
  5. namespace AppSettingsDemo.Helpers  
  6. {  
  7.     /// <summary>  
  8.     /// This is the Settings static class that can be used in your Core solution or in any  
  9.     /// of your client applications. All settings are laid out the same exact way with getters  
  10.     /// and setters.   
  11.     /// </summary>  
  12.     public static class UserSettings  
  13.     {  
  14.         static ISettings AppSettings{  
  15.             get{  
  16.                 return CrossSettings.Current;  
  17.             }  
  18.         }  
  19.   
  20.         public static string UserName{  
  21.             get => AppSettings.GetValueOrDefault(nameof(UserName), string.Empty);  
  22.             set => AppSettings.AddOrUpdateValue(nameof(UserName), value);  
  23.         }  
  24.   
  25.         public static string MobileNumber  
  26.         {  
  27.             get => AppSettings.GetValueOrDefault(nameof(MobileNumber), string.Empty);  
  28.             set => AppSettings.AddOrUpdateValue(nameof(MobileNumber), value);  
  29.         }  
  30.   
  31.         public static string Email  
  32.         {  
  33.             get => AppSettings.GetValueOrDefault(nameof(Email), string.Empty);  
  34.             set => AppSettings.AddOrUpdateValue(nameof(Email), value);  
  35.         }  
  36.   
  37.         public static string Password  
  38.         {  
  39.             get => AppSettings.GetValueOrDefault(nameof(Password), string.Empty);  
  40.             set => AppSettings.AddOrUpdateValue(nameof(Password), value);  
  41.         }  
  42.   
  43.         public static void ClearAllData()  
  44.         {  
  45.             AppSettings.Clear();  
  46.         }   
  47.     }  
  48. }  

Step 4:

Below view model will helpful to store/read string values(UserName, MobileNumber , Email , Password). And we are maintaining common properties for UserLogicViewModel, DetailsPageViewModel by Inheriting BasePageViewModel.

BasePageViewModel.cs


  1. using System.ComponentModel;  
  2. using System.Runtime.CompilerServices;  
  3. using AppSettingsDemo.Helpers;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace AppSettingsDemo.ViewModels  
  7. {  
  8.     public class BasePageViewModel : INotifyPropertyChanged  
  9.     {  
  10.   
  11.         public INavigation _navigation;  
  12.         public string UserName  
  13.         {  
  14.             get => UserSettings.UserName;  
  15.             set  
  16.             {  
  17.                 UserSettings.UserName = value;  
  18.                 NotifyPropertyChanged("UserName");  
  19.             }  
  20.         }  
  21.   
  22.         public string MobileNumber  
  23.         {  
  24.             get => UserSettings.MobileNumber;  
  25.             set  
  26.             {  
  27.                 UserSettings.MobileNumber = value;  
  28.                 NotifyPropertyChanged("MobileNumber");  
  29.             }  
  30.         }  
  31.   
  32.         public string Email  
  33.         {  
  34.             get => UserSettings.Email;  
  35.             set  
  36.             {  
  37.                 UserSettings.Email = value;  
  38.                 NotifyPropertyChanged("Email");  
  39.             }  
  40.         }  
  41.   
  42.         public string Password  
  43.         {  
  44.             get => UserSettings.Password;  
  45.             set  
  46.             {  
  47.                 UserSettings.Password = value;  
  48.                 NotifyPropertyChanged("Password");  
  49.             }  
  50.         }  
  51.  
  52.         #region INotifyPropertyChanged      
  53.         public event PropertyChangedEventHandler PropertyChanged;  
  54.         protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")  
  55.         {  
  56.             PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  57.         }  
  58.         #endregion  
  59.     }  
  60. }  

Step 5:

Create your own Xaml page named UserLogin.xaml for user login. and here we are binding the values like UserName, Mobilenumber, Email, Password from BaseViewModel and LoginCommand is for navigate to DetailsPage.

UserLogin.xaml

  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" BackgroundColor="#EEEEEE" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="AppSettingsDemo.Views.UserLogin">    
  3.     <ContentPage.Content>    
  4.         <StackLayout Padding="30,80,30,0">    
  5.             <Label Text="User Settings" TextColor="#533F95" FontSize="25" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center"/>    
  6.             <StackLayout Spacing="15" VerticalOptions="CenterAndExpand">    
  7.                 <Entry Placeholder="User Name" Text="{Binding UserName}" HorizontalOptions="FillAndExpand" HeightRequest="40"/>    
  8.                 <Entry Placeholder="Mobile Number" Keyboard="Numeric" Text="{Binding MobileNumber}" HorizontalOptions="FillAndExpand" HeightRequest="40"/>    
  9.                 <Entry Placeholder="Email Address" Keyboard="Email" Text="{Binding Email}" HorizontalOptions="FillAndExpand" HeightRequest="40"/>    
  10.                 <Entry Placeholder="Password" IsPassword="true" Text="{Binding Password}" HorizontalOptions="FillAndExpand" HeightRequest="40"/>    
  11.                 <Button Text="Login" TextColor="White" BackgroundColor="#533F95" FontAttributes="Bold" BorderColor="White" BorderWidth="0.5" BorderRadius="10" HorizontalOptions="FillAndExpand" Command="{Binding LoginCommand}"/>    
  12.             </StackLayout>    
  13.         </StackLayout>    
  14.     </ContentPage.Content>    
  15. </ContentPage>    

Make BindingContext in code behind with UserLoginPageViewModel

UserLogin.xaml.cs
  1. using AppSettingsDemo.ViewModels;  
  2. using Xamarin.Forms;  
  3.   
  4. namespace AppSettingsDemo.Views  
  5. {  
  6.     public partial class UserLogin : ContentPage  
  7.     {  
  8.         public UserLogin()  
  9.         {  
  10.             InitializeComponent();  
  11.             NavigationPage.SetHasNavigationBar(this, false);  
  12.             BindingContext = new UserLoginPageViewModel(Navigation);  
  13.         }  
  14.     }  
  15. }  

Below view model will helpful to store string values (UserName, Password, MobileNumber) and also for user login.


UserLoginPageViewModel.cs


  1. using System.Windows.Input;  
  2. using Xamarin.Forms;  
  3.   
  4. namespace AppSettingsDemo.ViewModels  
  5. {  
  6.     public class UserLoginPageViewModel : BasePageViewModel  
  7.     {  
  8.   
  9.         public ICommand LoginCommand { getprivate set; }  
  10.   
  11.         public UserLoginPageViewModel(INavigation navigation)  
  12.         {  
  13.             _navigation = navigation;  
  14.   
  15.             LoginCommand = new Command(() => UpdateUserInfo());  
  16.         }  
  17.   
  18.         void UpdateUserInfo()  
  19.         {  
  20.             _navigation.PushAsync(new Views.DetailsPage());  
  21.         }  
  22.     }  
  23. }  

Step 6:

Create your own Xaml page named DetailsPage.xaml for showing user login values and also for user logout. And here we binding the values from BaseViewModel like UserName, Mobilenumber, Email, Password, LogoutCommand.

DetailsPage.xaml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" BackgroundColor="#EEEEEE" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="AppSettingsDemo.Views.DetailsPage">  
  3.     <ContentPage.Content>  
  4.         <StackLayout Padding="40" Spacing="30">      
  5.             <Label Text="User Details" TextColor="#533F95" FontSize="25" HorizontalOptions="CenterAndExpand" HorizontalTextAlignment="Center"/>   
  6.             <StackLayout Spacing="25">  
  7.                 <StackLayout>  
  8.                     <Label Text="User Name:" Font="18" TextColor="Black" HorizontalOptions="FillAndExpand"/>  
  9.                     <Label Text="{Binding UserName}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>  
  10.                 </StackLayout>   
  11.                 <StackLayout>   
  12.                     <Label Text="Mobile Number:" Font="18" HorizontalOptions="FillAndExpand" TextColor="Black"/>  
  13.                     <Label Text="{Binding MobileNumber}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>  
  14.                 </StackLayout>   
  15.                 <StackLayout>   
  16.                     <Label Text="Email Address:" Font="18" HorizontalOptions="FillAndExpand" TextColor="Black"/>  
  17.                     <Label Text="{Binding Email}" HorizontalOptions="FillAndExpand" TextColor="Gray"/>  
  18.                 </StackLayout>   
  19.             </StackLayout>   
  20.             <Button Text="Logout" TextColor="#533F95" BackgroundColor="Transparent" WidthRequest="100" FontAttributes="Bold" BorderColor="#533F95" BorderWidth="1" BorderRadius="10" HorizontalOptions="EndAndExpand" Command="{Binding LogoutCommand}"/>  
  21.         </StackLayout>       
  22.     </ContentPage.Content>  
  23. </ContentPage>  

    Make BindingContext in code behind with Details DetailsPageViewModel.

    DetailsPage.xaml.cs

    1. using AppSettingsDemo.ViewModels;  
    2. using Xamarin.Forms;  
    3.   
    4. namespace AppSettingsDemo.Views  
    5. {  
    6.     public partial class DetailsPage : ContentPage  
    7.     {  
    8.         public DetailsPage()  
    9.         {  
    10.             InitializeComponent();  
    11.             BindingContext = new DetailsPageViewModel(Navigation);  
    12.         }  
    13.     }  
    14. }  

    Below view model will helpful to read string values (UserName, Password, MobileNumber) from app settings.

    DetailsPageViewModel.cs
    1. using System.Windows.Input;  
    2. using AppSettingsDemo.Helpers;  
    3. using AppSettingsDemo.Views;  
    4. using Xamarin.Forms;  
    5.   
    6. namespace AppSettingsDemo.ViewModels  
    7. {  
    8.     public class DetailsPageViewModel : BasePageViewModel  
    9.     {  
    10.         public ICommand LogoutCommand { getprivate set; }  
    11.         public DetailsPageViewModel(INavigation navigation)  
    12.         {  
    13.             _navigation = navigation;  
    14.             LogoutCommand = new Command(() => ResetUserInfo());  
    15.         }  
    16.   
    17.         void ResetUserInfo()  
    18.         {  
    19.             _navigation.PushAsync(new UserLogin());  
    20.             UserSettings.ClearAllData();  
    21.         }  
    22.     }  
    23. }  

    In LogoutCommand we are navigating to UserLogin page and calling UserSettings.ClearAllData() it will clear the all data what ever we are storing in app settings.

    Output:

    iOS:



    Android:



    Source Code:


    No comments:

    Post a Comment