Find a Contact

PDF for offline use
Related Articles:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2016-06

This recipe shows how to find a contact using the ABAddressBook class.

Recipe

By using an instance of the CNContactStore class, you can fetch contact information from the user's contacts database. The CNContactStore contains all of the methods required for fetching or updating contacts and groups from the database.

Design your UI

Design your app's User Interface that will be used to find the Contact and present it. For example, a UIButton to find the Contact and a UITextField to present it:

Find an Existing Contact

Find an existing Contact and present it when the user clicks the button. For example:

using System;
using Foundation;
using Contacts;
using ContactsUI;
using UIKit;

namespace ContactAccess
{
    public partial class ViewController : UIViewController
    {
        protected ViewController (IntPtr handle) : base (handle)
        {

        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
        }

        partial void FindContact_TouchUpInside (UIButton sender)
        {
            // Create predicate to locate requested contact
            var predicate = CNContact.GetPredicateForContacts ("Appleseed");

            // Define fields to be searched
            var fetchKeys = new NSString [] { CNContactKey.GivenName, CNContactKey.FamilyName };

            // Grab matching contacts
            var store = new CNContactStore ();
            NSError error;
            var contacts = store.GetUnifiedContacts (predicate, fetchKeys, out error);

            // Found?
            if (contacts.Length > 0) {
                // Get the first matching contact
                var contact = contacts [0];

                // Display it
                FoundContact.Text = string.Format ("{0} {1}", contact.GivenName, contact.FamilyName);
            } else {
                // Not found
                FoundContact.Text = "";
            }
        }
    }
}

Let's look at this code in detail:

  1. First, it defines what to search for in a Contact (CNContact.GetPredicateForContacts ("Appleseed")). In this case, it is hunting for any Contact that contains the text Appleseed.
  2. Next, define what values to return: var fetchKeys = new NSString [] { CNContactKey.GivenName, CNContactKey.FamilyName }.
  3. Then it accesses the Contact Store (CNContactStore) and fetches the matching contacts: var contacts = store.GetUnifiedContacts (predicate, fetchKeys, out error).
  4. Finally, it displays the first Contact found.

Additional Information

For more information, please see our Contacts and ContactUI documentation.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.