When developing with Xamarin.Forms, you will quickly find yourself in a situation where some of the native platforms’ functionalities were not implemented in the Forms API. In these situations, you can use the power of a Dependency Service to access the native Xamarin for each platform.
For example, say you want to access the devices’ GPS functionality. Each platform has GPS capabilities, yet function slightly differently. In a situation like this, using a dependency service will provide you access to all the native functionality on each platform within the shared code of the portable class library (PCL).
A dependency service is exactly what it sounds like. Within the PCL project, you will have a service (interface) that abstracts the functionality that you need access to in each platform. Within each platform project, you will create the native implementation that correlates with your shared abstraction.
Let’s go ahead and implement a simple dependency service. Forms does not provide access to your application’s cookie storage. While the cookie storage is handled automatically for WebViews and other network requests, you may need to access the cookies directly.
1. Within the PCL project, create an interface file called: INativeCookieService.cs
2. Add the methods and properties you are abstracting
3. Within the Android project, create a class called: NativeCookieService.cs
4. Add the assembly attribute:
5. Have the class implement: INativeCookieService
6. Add the native functionality
7. Repeat steps 3 – 6 for iOS (and Windows if you are supporting Windows). Make sure to use the iOS namespace rather than the Android on step 4
Whenever you need to use the native functionality within the PCL, you simply make the call: