How to use platform specific code
If you are building Xamarin.Forms Apps you will certainly encouter the problem that you have to use platform specific code to get some specific platform or hardware functions to work. Dependency Service allow you’re apps to call the platform specific code out of your shared code basis. So basically you define a interface and the Dependency Service finds the correct implementation of the interface for the required platform.
What do we need?
To get started with Dependency Service we need the following things:
- The Interface – You define a interface with the required functions in you’re shared code basis.
- Implementation per Platform – Write platform specific implementation in each platform project.
- Registrate Implementation – Register your class with a DependencyService metadata attribute. This is neccesary so the Dependency Service could find your implementaion class
To show you how to create and use such a Dependency Service we are going to create a service to get the screen dimension of the current device.
To do so the first thing we need to do is to create the interface for this service.
To get the screen dimension of the current device we need to methods. One will return the height and one will return the width.
The interface will look like this:
Now we have a interface we can use in the shared code to get the platform specific values. The next step is to tell Xamarin where the platform specific code is.
To do so we have to implement the interface in the platform projects.
The implementation of the interface in iOS will look like this:
There is nothing special on the interface implementation just do it like you are used to do. Thge only extra thing you have to do is to add the assembly attribute above the namespace. This tells Xamarin that this implementation belongs to the dependency interface. This registrates the implementation and you are ready to call the dpendency interface from the previous step into your shared code.
Beneath you will find the Android implementation of the depency service interface.
If you have all this things up and running you are able to use the dependency service interface and Xamarin take care of the rest.
Here is an example on how to use the dependency service in the shared code:
Thats all you need to do to implement platform specific code into you’re Xamarin.Forms app.