Introduction
In this article, the purpose of the code is to fetch contact details from iOS device.
For OS version < 9.0 'ABAddressBook
' is used for performing any operation related to contact. But after OS version 9.0, 'CNContact
' is used for the same.
So, here, we fetch the contact information by using 'CNContact
' which is used for OS version >= 9.0.
Here we go.....
Using the Code
Basic Step
- Create a new Project with name '
Read-Contact
'. On the File menu, click New Project.
- Select 'Single View App (iPhone)' project and name it as '
Read-Contact
'.
Under Installed > Visual C# > iOS > iPhone > Single View App (iPhone)
Step 01: We need to add the Permission Key in plist.info
Right click on 'info.plist' and select 'Open with...' then select 'Automatic Editor Selector (XML)' and then paste below 'key' and 'value' over there.
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
Step 02: We need to create a view model class for contact. So, create a new class with name 'ContactVm' and add below properties in that class.
public IList EmailId { get; set; }
public IList PhoneNumbers { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
public bool IsSelected { get; set; }
Step 03: Create the below method to fetch contact from iOS device. Comments added to each line for breakdown the code.
public List<ContactVm> ReadContacts()
{
var response = new List<ContactVm>();
try
{
var keysToFetch = new[] { CNContactKey.PhoneNumbers,
CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses };
var containerId = new CNContactStore().DefaultContainerIdentifier;
using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
{
CNContact[] contactList;
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysToFetch, out var error);
}
response.AddRange(from item in contactList
where item?.EmailAddresses != null
select new ContactVm
{
PhoneNumbers = item.PhoneNumbers,
GivenName = item.GivenName,
FamilyName = item.FamilyName,
EmailId = item.EmailAddresses.Select
(m => m.Value.ToString()).ToList()
});
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return response;
}
HERE ALL IS DONE..........