在Xamarin中编写设备平台特定代码,

4xy9mtcn  于 2022-12-28  发布在  其他
关注(0)|答案(5)|浏览(140)

我有以下Xamarin.Forms.ContentPage类结构

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)
        {
            //I would to write device specific code to write to the access token to the device
            //Example of saving the access token to iOS device
            NSUserDefaults.StandardUserDefaults.SetString(accessToken, "AccessToken");

            //Example of saving the access token to Android device
            var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
            var prefsEditor = prefs.Edit();

            prefEditor.PutString("AccessToken", accessToken);
            prefEditor.Commit();
        }
    }
}

我想在MyPageLogIn方法中编写特定于平台的代码,以便根据他们使用我的应用程序的设备操作系统来保存访问令牌。
当用户在其设备上使用我的应用程序时,如何仅运行设备特定代码?

kx1ctssn

kx1ctssn1#

这是一个很容易通过依赖注入解决的场景。
在共享代码或PCL代码上提供与所需方法的接口,例如:

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

在该接口的App类上有一个属性:

public class App 
{
    public static IUserPreferences UserPreferences { get; private set; }

    public static void Init(IUserPreferences userPreferencesImpl) 
    {
        App.UserPreferences = userPreferencesImpl;
    }

    (...)
}

在目标项目上创建特定于平台的实现:
iOS系统:

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

    public string GetString(string key)
    {
        return NSUserDefaults.StandardUserDefaults.StringForKey(key);
    }
}

安卓系统:

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)
    {
        (...)
    }
}

然后在每个特定于平台的项目上创建IUserPreferences的实现,并使用App.Init(new iOSUserPrefernces())App.Init(new AndroidUserPrefernces())方法对其进行设置。
最后,您可以将代码更改为:

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);
        }
    }
}
k3fezbri

k3fezbri2#

Xamarin。表2.3.4为此引入了一种新方法:

if (Device.RuntimePlatform == Device.Android)
{
    // Android specific code
}
else if (Device.RuntimePlatform == Device.iOS)
{
    // iOS specific code
}
else if (Device.RuntimePlatform == Device.UWP)
{
    // UWP specific code
}

也有其他平台可供选择,你可以在VisualStudio中输入Device.,它会向你显示选项。

kd3sttzy

kd3sttzy3#

答案有多种,取决于您想要实现的目标和您拥有的项目类型:

在不同的平台上执行不同的Xamarin.Forms代码。

例如,如果您希望在不同的平台上使用不同的字体大小,请使用此选项:

label.Font = Device.OnPlatform<int> (12, 14, 14);

在共享(PCL)项目中执行特定于平台的代码常见的模式是使用DI(依赖注入)。Xamarin.Forms为此提供了一个简单的DependencyService,但可以使用任何您想要的。
在共享中执行平台特定代码(共享资产项目)项目由于代码是按平台编译的,因此您可以将平台特定的代码 Package 在#if __PLATFORM__#endif中,并将所有代码放在同一个文件中。平台项目应定义__IOS____ANDROID____WINDOWS_PHONE__。请注意,包含Xaml和代码的共享资产项目无法在Xamarin.Studio上的iOS上正常工作,并且使用编译器指令会使代码更难阅读和测试。

xfyts7mz

xfyts7mz4#

Xamarin.Forms有一个内置的依赖注入器,如果你看一下他们网站开发者区域的指南(http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/
您还可以从NuGet/Github(https://github.com/aritchie/acr-xamarin-forms)中调用一个很棒的库,它将处理您正在寻找的存储需求...看看其中的Settings服务,它甚至可以处理更复杂对象的序列化。

zed5wv10

zed5wv105#

这似乎与Xamarin.Forms无关,而更多的是关于在PCL中使用默认值。
然后只需要调用他的静态方法来设置/检索。nuget包是Xam.Plugins.Settings
它可以像这样使用:

using Refractored.Xam.Settings;

...

CrossSettings.Current.AddOrUpdateValue("AccessToken", accessToken);
var value = CrossSettings.Current.GetValueOrDefault<string>("AccessToken");

相关问题