【问题标题】:how to access the methods in iOS/Android projects code from PCL project如何从 PCL 项目访问 iOS/Android 项目代码中的方法
【发布时间】:2017-01-27 10:53:06
【问题描述】:

在我的 Xamarin Studio for MAC 中,我使用“Xamarin.Forms”解决方案。我有3个项目。 PCL、iOS 和安卓。 我有一个代理类(webservice 类),我将文件“checkServices.cs”复制到 iOS 和 Android 项目中。我还在“iOS”和“Android”项目中添加了 System.Web.Webservices 引用。

PCL 在 iOS 和 Android 中被引用,但不能反过来引用。分享只是单一的方式。来自 PCL --> iOS/Andoroid!

现在如何从我的 PCL 调用这些方法将数据放在 XAML 页面上?我喜欢从位于 iOS/Android 项目文件夹中的 PCL 调用方法。

【问题讨论】:

标签: xamarin xamarin.forms


【解决方案1】:

为此,您需要使用Dependency Service

简而言之,在您的 PCL 中声明一个接口,该接口定义您想要使用的方法,例如:

public interface ITextToSpeech
{
    void Speak (string text);
}

这可能是文本到语音实现的接口。现在在您的平台特定项目中实现该接口。对于 iOS,它可能如下所示:

using AVFoundation;

public class TextToSpeechImplementation : ITextToSpeech
{
    public TextToSpeechImplementation () {}

    public void Speak (string text)
    {
        var speechSynthesizer = new AVSpeechSynthesizer ();

        var speechUtterance = new AVSpeechUtterance (text) {
            Rate = AVSpeechUtterance.MaximumSpeechRate/4,
            Voice = AVSpeechSynthesisVoice.FromLanguage ("en-US"),
            Volume = 0.5f,
            PitchMultiplier = 1.0f
        };

        speechSynthesizer.SpeakUtterance (speechUtterance);
    }
}

这是重要的部分:在命名空间上方用这个属性标记它。 [assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechImplementation))]

您还需要将适当的 using 添加到您的项目中。

现在,在运行时,根据您所运行的平台,将为接口加载正确的实现。所以对于Android你做的完全一样,只是Speak方法的实现会有所不同。

在 PCL 中,您现在可以像这样访问它:DependencyService.Get<ITextToSpeech>().Speak("Hello from Xamarin Forms");

您可能应该检查DependencyService.Get<ITextToSpeech>() 方法是否不为空,这样您的应用程序就不会在您做错事时崩溃。但这应该涵盖基础知识。

【讨论】:

  • 你是最棒的,也是最棒的。我苦苦挣扎了将近 2 周来制定我的问题并找到解决方案....再次非常感谢您....您是救生员 :)
  • 反过来呢,在 Droid 中调用 PCL 方法?
  • 不可能,因为它会创建循环引用。从您的 pcl 公开事件或使用消息中心
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 2017-05-14
  • 2023-04-05
相关资源
最近更新 更多