Introduction
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are the most easily done tasks using native file APIs on each platform. Alternatively, embedded resources are also a simpler solution to distribute the data files with an app.
DependencyService
DependencyService allows apps to call into platform-specific functionality from shared code. This functionality enables Xamarin.Forms apps to do anything that a native app can do.
DependencyService is a dependency resolver. In practice, an interface is defined and DependencyService finds the correct implementation of that interface from the various platform projects.
Xamarin.Forms apps need three components to use DependencyService
- Interface – The required functionality is defined by an interface in shared code.
- Implementation Per Platform – Classes that implement the interface must be added to each platform project.
- Registration – Each implementing class must be registered with DependencyService via a metadata attribute. Registration enables DependencyService to find the implementing class and supply it in place of the interface at runtime.
- Call to DependencyService – Shared code needs to explicitly call DependencyService to ask for implementations of the interface.
Prerequisites
- Visual Studio 2017 (Windows or Mac)
Setting up a Xamarin.Forms Project
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.
Choose the Cross-platform App project under Visual C#-->Cross-platform in the New Project dialog.
Now Select the Blank App and Choose Portable Class Library (PCL).
You now have a basic Xamarin.Forms app. Click the Play button to try it out.
Creating Interface
Create - interface in Xamarin.Forms PCL.
Go to Solution—>PCL—>Right click—>New—>Interface—>IContacts.cs.
Now, write the following code.
IContacts.cs
- namespace XamarinFormscContacts
- {
- public interface IContacts
- {
- Task<List<ContactLists>> GetDeviceContactsAsync();
- }
- }
Creating Model
Go to Solution—>PCL—>Right click—>New—>Class—>ContactLists.cs.
Now, write the following code for holding Contacts.
ContactLists.cs
- namespace XamarinFormscContacts {
- public class ContactLists {
- public string DisplayName {
- get;
- set;
- }
-
- public string ContactNumber {
- get;
- set;
- }
- }
- }
Implementation per platform-Android Implementation
Go to Solution—>Android —>Right click—>New—>Class—> ContactHelper.cs
Now, write the following code for Picking Contacts.
ContactHelper.cs
- [assembly: Dependency(typeof(ContactHelper))]
- namespace XamarinFormscContacts.Droid {
- class ContactHelper: IContacts {
- public async Task < List < ContactLists >> GetDeviceContactsAsync() {
- ContactLists selectedContact = new ContactLists();
- List < ContactLists > contactList = new List < ContactLists > ();
- var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
- string[] projection = {
- ContactsContract.Contacts.InterfaceConsts.Id,
- ContactsContract.Contacts.InterfaceConsts.DisplayName,
- ContactsContract.CommonDataKinds.Phone.Number
- };
- var cursor = Xamarin.Forms.Forms.Context.ContentResolver.Query(uri, projection, null, null, null);
- if (cursor.MoveToFirst()) {
- do {
- contactList.Add(new ContactLists() {
- DisplayName = cursor.GetString(cursor.GetColumnIndex(projection[1]))
- });
- } while (cursor.MoveToNext());
- }
- return contactList;
- }
- private object ManagedQuery(Android.Net.Uri uri, string[] projection, object p1, object p2, object p3) {
- throw new NotImplementedException();
- }
- }
- }
UWP Implementation
Go to Solution—>UWP —>Right click—>New—>Class—> ContactHelper.cs
Now, write the following code for Picking Contacts.
ContactHelper.cs
- [assembly: Xamarin.Forms.Dependency(typeof(ContactHelper))]
- namespace XamarinFormscContacts.UWP {
- public class ContactHelper: IContacts {
- public async Task < List < ContactLists >> GetDeviceContactsAsync() {
- List < ContactLists > selectedContact = new List < ContactLists > ();
- var contactPicker = new ContactPicker();
- contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
- Contact contact = await contactPicker.PickContactAsync();
-
- selectedContact.Add(new ContactLists() {
- DisplayName = contact.SortName, ContactNumber = contact.YomiDisplayName
- });
- return selectedContact;
- }
-
- }
- }
Setting up the User Interface.
Go to MainPage.Xaml and write the following code.
MainPage.Xaml
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:XamarinFormscContacts" x:Class="XamarinFormscContacts.MainPage">
- <ContentPage.Content>
- <StackLayout>
- <Button x:Name="btnPick" Text="Pick Contact" Clicked="Button_Clicked"></Button>
- <ListView x:Name="listContact">
- <ListView.ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <StackLayout>
- <Label Text="{Binding DisplayName}"></Label>
- </StackLayout>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackLayout>
- </ContentPage.Content>
- </ContentPage>
Call to DependencyService
In this step, call the DependencyService for your PCL.
MainPage.Xaml.cs
- namespace XamarinFormscContacts {
- public partial class MainPage: ContentPage {
- public MainPage() {
- InitializeComponent();
- }
- private async void Button_Clicked(object sender, EventArgs e) {
- switch (Device.RuntimePlatform) {
- case Device.UWP:
- var selectContact = await DependencyService.Get < IContacts > ().GetDeviceContactsAsync();
- listContact.ItemsSource = selectContact;
- break;
- case Device.Android:
- var ContactList = await DependencyService.Get < IContacts > ().GetDeviceContactsAsync();
- listContact.ItemsSource = ContactList;
- break;
- default:
- break;
- }
- }
- }
-
- }
In this step give permission to access contacts form Android devices.
In this step give permission to access contacts from Windows devices
Click the
Play button to try it out.
I hope you have understood how to pick the contacts using DependencyService.
Thanks for reading. Please share comments and feedback.