4
votes

In my Xamarin Studio for MAC I use "Xamarin.Forms" solution. I've 3 projects. PCL , iOS and Android. I've a proxyclass (webservice class) which I copied the file "checkServices.cs" into the iOS and Android projects. I also added the System.Web.Webservices reference in the "iOS" and "Android" project.

The PCL is referenced in iOS and in Android, but can not reference vice versa. The sharing is only single way. from PCL --> iOS/Andoroid!

Now how can I call these methods from my PCL to put the data on XAML page ? I like to call the methods from PCL which are located in iOS/Android project folder.

1

1 Answers

10
votes

For this you will need to use the Dependency Service.

In short, in your PCL declare an interface which defines the methods that you would want to use, for example:

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

This could be an interface for a text-to-speech implementation. Now in your platform-specific projects implement the interface. For iOS it could look like this:

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

Here is the important part: mark it with this attribute above the namespace. [assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechImplementation))]

You will also need to add the appropriate using to your project.

Now, at runtime, depending on the platform you are running on the right implementation will be loaded for the interface. So for Android you do exactly the same, only the implementation of the Speak method will be different.

In the PCL you can now access it like: DependencyService.Get<ITextToSpeech>().Speak("Hello from Xamarin Forms");

You should probably check if the DependencyService.Get<ITextToSpeech>() method is not null so your app doesn't crash when you did something wrong. But this should cover the basics.