首页 文章

如何从PCL项目中访问iOS / Android项目代码中的方法

提问于
浏览
4

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

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

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

1 回答

  • 10

    为此,您需要使用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))]

    您还需要将适当的使用添加到项目中 .

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

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

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

相关问题