[Xamarin] How to access user’s contacts ?

March 10th, 2014 | Posted by Tom in .NET | Article | Windows Phone | WPF | Read: 3,988

In my previous article about Xamarin, I’ve explained a way to access user’s contact by using the ManagedQuery API. Even if the code is working fine, you may think that it can be a bit “hard” to understand, when the only goal is to query the contacts.

Today, I’ll talk about Xamarin.Mobile, a library that exposes some APIs to access user’s contacts, user’s position and to allow you to, easily, take a picture in your application. The interesting point here is the fact that the API is available for iOS, Android and Windows Phone.

To use Xamarin.Mobile, you need to download the binaries. Thanks to the Components Store available (something that’s a bit similar to Nuget), you can get them easily:

image image

After you hit the “Add to App” button, the component is downloaded and the reference is added to your project:

image image

Once the reference is added, the first step is to add the following “using”:

using Xamarin.Contacts;

Now, by using the AddressBook class, we are able to access to the user’s contacts and we can use LINQ, which provides a more easier and comfortable syntax:

var addressBook = new AddressBook(this);
if (!await addressBook.RequestPermission())
{
    // We don't have the permission to access user's contacts: check if the READ_CONTACTS has been set
}
else
{
    var companyContacts = addressBook.Where(c => c.Organizations.Any(o => o.Name == "Infinite Square"));
    if (companyContacts.Any())
    {
        foreach (var contact in companyContacts)
        {
            var lastName = contact.LastName;
            var firstName = contact.FirstName;
            var thumbnailBitmap = contact.GetThumbnail();
        }
    }
}

As you can see, the code is really easy to understand and maintainable!

 

If you want to know more about Xamarin.Mobile (or just check how does it work), feel free to go to Github, where you’ll be able to find the sources: https://github.com/xamarin/Xamarin.Mobile

 

Happy (Xamarin) coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply