Xamarin.Forms DependencyService iOS implementation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The interface you defined needs to be implemented in every targeted platform. For iOS this is done through the AVFoundation framework. The following implementation of the ITextToSpeech interface handles speaking a given text in English.

using AVFoundation;

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

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

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

        speechSynthesizer.SpeakUtterance (speechUtterance);
    }
}

When you've created your class you need to enable the DependencyService to discover it at run time. This is done by adding an [assembly] attribute above the class definition and outside of any namespace definitions.

using AVFoundation;
using DependencyServiceSample.iOS;

[assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechiOS))]
namespace DependencyServiceSample.iOS {
    public class TextToSpeechiOS : ITextToSpeech
...

This attribute registers the class with the DependencyService so it can be used when an instance of the ITextToSpeech interface is needed.



Got any Xamarin.Forms Question?