Xamarin.Forms - Contact Picker Using DependencyService

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.

Xamarin

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 
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.

Xamarin
 
Now Select the Blank App and Choose Portable Class Library (PCL).

Xamarin 
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Xamarin
 
Creating Interface

Create - interface in Xamarin.Forms PCL.

Go to Solution—>PCL—>Right click—>New—>Interface—>IContacts.cs.

Xamarin
 
Now, write the following code.

IContacts.cs
Xamarin
  1. namespace XamarinFormscContacts  
  2. {  
  3.    public interface IContacts  
  4.       {  
  5.          Task<List<ContactLists>> GetDeviceContactsAsync();  
  6.       }  
  7. }  
Creating Model

Go to Solution—>PCL—>Right click—>New—>Class—>ContactLists.cs.

Xamarin 

Now, write the following code for holding Contacts.
 
ContactLists.cs

Xamarin
  1. namespace XamarinFormscContacts {  
  2.     public class ContactLists {  
  3.         public string DisplayName {  
  4.             get;  
  5.             set;  
  6.         }  
  7.   
  8.         public string ContactNumber {  
  9.             get;  
  10.             set;  
  11.         }  
  12.     }  
  13. }  
Implementation per platform-Android Implementation

Go to Solution—>Android —>Right click—>New—>Class—> ContactHelper.cs

Xamarin
 
Now, write the following code for Picking Contacts.

ContactHelper.cs

Xamarin 
  1. [assembly: Dependency(typeof(ContactHelper))]  
  2. namespace XamarinFormscContacts.Droid {  
  3.     class ContactHelper: IContacts {  
  4.         public async Task < List < ContactLists >> GetDeviceContactsAsync() {  
  5.             ContactLists selectedContact = new ContactLists();  
  6.             List < ContactLists > contactList = new List < ContactLists > ();  
  7.             var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;  
  8.             string[] projection = {  
  9.                 ContactsContract.Contacts.InterfaceConsts.Id,  
  10.                 ContactsContract.Contacts.InterfaceConsts.DisplayName,  
  11.                 ContactsContract.CommonDataKinds.Phone.Number  
  12.             };  
  13.             var cursor = Xamarin.Forms.Forms.Context.ContentResolver.Query(uri, projection, nullnullnull);  
  14.             if (cursor.MoveToFirst()) {  
  15.                 do {  
  16.                     contactList.Add(new ContactLists() {  
  17.                         DisplayName = cursor.GetString(cursor.GetColumnIndex(projection[1]))  
  18.                     });  
  19.                 } while (cursor.MoveToNext());  
  20.             }  
  21.             return contactList;  
  22.         }  
  23.         private object ManagedQuery(Android.Net.Uri uri, string[] projection, object p1, object p2, object p3) {  
  24.             throw new NotImplementedException();  
  25.         }  
  26.     }  
  27. }  
UWP Implementation

Go to Solution—>UWP —>Right click—>New—>Class—> ContactHelper.cs

Xamarin
 
Now, write the following code for Picking Contacts.

ContactHelper.cs

Xamarin 
  1. [assembly: Xamarin.Forms.Dependency(typeof(ContactHelper))]  
  2. namespace XamarinFormscContacts.UWP {  
  3.     public class ContactHelper: IContacts {  
  4.         public async Task < List < ContactLists >> GetDeviceContactsAsync() {  
  5.             List < ContactLists > selectedContact = new List < ContactLists > ();  
  6.             var contactPicker = new ContactPicker();  
  7.             contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);  
  8.             Contact contact = await contactPicker.PickContactAsync();  
  9.   
  10.             selectedContact.Add(new ContactLists() {  
  11.                 DisplayName = contact.SortName, ContactNumber = contact.YomiDisplayName  
  12.             });  
  13.             return selectedContact;  
  14.         }  
  15.   
  16.     }  
  17. }  
Setting up the User Interface.

Go to MainPage.Xaml and write the following code.

Xamarin 
MainPage.Xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <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">  
  3.     <ContentPage.Content>  
  4.         <StackLayout>  
  5.             <Button x:Name="btnPick" Text="Pick Contact" Clicked="Button_Clicked"></Button>  
  6.             <ListView x:Name="listContact">  
  7.                 <ListView.ItemTemplate>  
  8.                     <DataTemplate>  
  9.                         <ViewCell>  
  10.                             <StackLayout>  
  11.                                 <Label Text="{Binding DisplayName}"></Label>  
  12.                             </StackLayout>  
  13.                         </ViewCell>  
  14.                     </DataTemplate>  
  15.                 </ListView.ItemTemplate>  
  16.             </ListView>  
  17.         </StackLayout>  
  18.     </ContentPage.Content>  
  19. </ContentPage>  
Call to DependencyService

In this step, call the DependencyService for your PCL.

Xamarin 

MainPage.Xaml.cs
  1. namespace XamarinFormscContacts {  
  2.     public partial class MainPage: ContentPage {  
  3.         public MainPage() {  
  4.             InitializeComponent();  
  5.         }  
  6.         private async void Button_Clicked(object sender, EventArgs e) {  
  7.             switch (Device.RuntimePlatform) {  
  8.                 case Device.UWP:  
  9.                     var selectContact = await DependencyService.Get < IContacts > ().GetDeviceContactsAsync();  
  10.                     listContact.ItemsSource = selectContact;  
  11.                     break;  
  12.                 case Device.Android:  
  13.                     var ContactList = await DependencyService.Get < IContacts > ().GetDeviceContactsAsync();  
  14.                     listContact.ItemsSource = ContactList;  
  15.                     break;  
  16.                 default:  
  17.                     break;  
  18.             }  
  19.         }  
  20.     }  
  21.   
  22. }  
In this step give permission to access contacts form Android devices.

Xamarin
In this step give permission to access contacts from Windows devices
Xamarin

Click the Play button to try it out.

Xamarin

Xamarin
 
I hope you have understood how to pick the contacts using DependencyService.
 
Thanks for reading. Please share comments and feedback.


Similar Articles