首页 > 解决方案 > 从共享中调用特定的 iOS/Android 例程

问题描述

我有一段在iOS中运行的代码:

  namespace Login.iOS
    {
    class Authenticate
    {
        public async Task LoginAsync()
        {
            var client = new Auth0Client(new Auth0ClientOptions

            {
                Domain = "difiore.auth0.com",
                ClientId = "Key goes here"
            });

                var loginResult = await client.LoginAsync();
            }
        }
    }

以及它对Android的等价物:

    namespace Login.Droid
    {
    class Authenticate
    {
        public async Task LoginAsync()
        {
            var client = new Auth0Client(new Auth0ClientOptions

            {
                Domain = "difiore.auth0.com",
                ClientId = "Key goes here"
            });

            var loginResult = await client.LoginAsync();
        }
    }
}

由于两者都依赖于专门为平台编写的库,因此它们必须是特定于平台的。

然后我有应该调用的共享代码:

    namespace Login
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        public MainPage ()
        {
            InitializeComponent ();
        }

        private void Login_Clicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new Authenticate());
        }
    }
}

但是代码行

Navigation.PushAsync(new Authenticate());

显然是错误的,因为它没有识别要调用的例程。

如何从共享的程序中调用特定于平台的例程?那是IOS和Android中的Authenticate类。

标签: xamarinxamarin.formsxamarin.iosxamarin.android

解决方案


您必须创建一个接口,以便使用Dependency Injection在共享或可移植类中调用平台特定类。按照此链接 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction。我希望这有帮助。


推荐阅读