Write device platform specific code in Xamarin.Forms

前端 未结 5 1504
野性不改
野性不改 2020-12-07 18:57

I have the following Xamarin.Forms.ContentPage class structure

public class MyPage : ContentPage
{
    public MyPage()
    {
        //do work t         


        
5条回答
  •  长情又很酷
    2020-12-07 19:34

    This is a scenario which is easily resolved with dependency injection.

    Have a interface with the desired methods on your shared or PCL code, like:

    public interface IUserPreferences 
    {
        void SetString(string key, string value);
        string GetString(string key);
    }
    

    Have a property on your App class of that interface:

    public class App 
    {
        public static IUserPreferences UserPreferences { get; private set; }
    
        public static void Init(IUserPreferences userPreferencesImpl) 
        {
            App.UserPreferences = userPreferencesImpl;
        }
    
        (...)
    }
    

    Create platform-specific implementations on your target projects:

    iOS:

    public class iOSUserPreferences : IUserPreferences 
    {
        public void SetString(string key, string value)
        {
            NSUserDefaults.StandardUserDefaults.SetString(key, value);
        }
    
        public string GetString(string key)
        {
            (...)
        }
    }
    

    Android:

    public class AndroidUserPreferences : IUserPreferences
    {
        public void SetString(string key, string value)
        {
            var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
            var prefsEditor = prefs.Edit();
    
            prefEditor.PutString(key, value);
            prefEditor.Commit();
        }
    
        public string GetString(string key)
        {
            (...)
        }
    }
    

    Then on each platform-specific project create an implementation of IUserPreferences and set it using either App.Init(new iOSUserPrefernces()) and App.Init(new AndroidUserPrefernces()) methods.

    Finally, you could change your code to:

    public class MyPage : ContentPage
    {
        public MyPage()
        {
            //do work to initialize MyPage 
        }
    
        public void LogIn(object sender, EventArgs eventArgs)
        {
            bool isAuthenticated = false;
            string accessToken = string.Empty;
    
            //do work to use authentication API to validate users
    
            if(isAuthenticated)
            {
                App.UserPreferences.SetString("AccessToken", accessToken);
            }
        }
    }
    

提交回复
热议问题