簡體   English   中英

在 Xamarin.Forms 中編寫特定於設備平台的代碼

[英]Write device platform specific code in Xamarin.Forms

我有以下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();
        }
    }
}

我想在MyPage LogIn方法中編寫特定於平台的代碼,以根據他們使用我的應用程序的設備操作系統保存訪問令牌。

當用戶在他們的設備上使用我的應用程序時,我如何只運行設備特定的代碼?

這是一個可以通過依賴注入輕松解決的場景。

在您的共享或 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(key, value);
    }

    public string GetString(string 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);
        }
    }
}

Xamarin.Forms 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
}

還有其他平台可供選擇,您可以輸入Device. 在 Visual Studio 中,它將顯示選項。

有多種答案,具體取決於您想要實現的目標以及您擁有的項目類型:

在不同平台上執行不同的Xamarin.Forms代碼。
例如,如果您希望在不同平台上使用不同的字體大小,請使用此命令:

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

在共享 (PCL) 項目中執行平台特定代碼常見模式是為此使用 DI(依賴注入)。 Xamarin.Forms提供了一個簡單的DependencyService ,但可以使用任何你想要的。

在共享(共享資產項目)項目中執行平台特定代碼由於代碼是按平台編譯的,您可以將平台特定代碼包裝在#if __PLATFORM__ #endif並將所有代碼放在同一個文件中。 平台項目應定義__IOS____ANDROID____WINDOWS_PHONE__ 請注意,包含Xaml和代碼的共享資產項目不適用於Xamarin.Studio iOS,並且具有編譯器指令會使您的代碼更難閱讀和測試。

這似乎與Xamarin.Forms而更多地與在 PCL 中使用默認值有關。 查看James Montemagno 的 github repo以進行跨平台默認設置。

然后只需調用他的靜態方法進行設置/檢索。 nuget 包是Xam.Plugins.Settings

它可以像這樣使用:

using Refractored.Xam.Settings;

...

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

Xamarin.Forms 有一個內置的依賴注入器,如果你在他們的網站 ( http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/ )

還有一個很棒的庫,您可以從 NuGet/Github ( https://github.com/aritchie/acr-xamarin-forms ) 中提取,它將處理您正在尋找的存儲要求......查看設置服務在那里,它甚至可以處理更復雜對象的序列化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM