Reputation: 47
I want to fetch all contact records in iOS Xamarin. I used code --> https://developer.xamarin.com/recipes/ios/shared_resources/contacts/find_a_contact/
Code:
public override void ViewDidLoad()
{
base.ViewDidLoad();
Util.CurrentView = this;
_View = this;
var predicate = CNContact.GetPredicateForContacts("Appleseed");
var fetchKeys = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName };
var store = new CNContactStore();
NSError error;
var contacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
}
Error code:
This Error: Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: +[CNContact predicateForContactsMatchingName:]: unrecognized selector sent to class 0x1a3e1ec
I already add [Export("predicateForContactsMatchingName:")]
, but it didn't help.
Upvotes: 1
Views: 709
Reputation: 865
"Appleseed" is the search term used in the example. Seems like your mismatch is because none of the contacts match with the predicate.
Anyways, during my own implementation I ran into many issues. Below is a full solution to fetch all contacts in iOS Xamarin.
First: Add permission in info.plist
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
Second: Create a Model for Contacts info
In the example below I only add 3 fields
using System.Collections;
/// <summary>
///
/// </summary>
namespace YourNameSpace
{
/// <summary>
///
/// </summary>
public class UserContact
{
public UserContact()
{
}
/// <summary>
///
/// </summary>
/// <param name="givenName"></param>
/// <param name="familyName"></param>
/// <param name="emailId"></param>
public UserContact(string givenName, string familyName, IList emailId)
{
GivenName = givenName;
FamilyName = familyName;
EmailId = emailId;
}
public bool IsSelected { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
public IList EmailId { get; set; }
}
}
Third: Read Contacts
public IEnumerable<UserContact> GetAllContactsAndEmails()
{
var keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses };
NSError error;
CNContact[] contactList;
var ContainerId = new CNContactStore().DefaultContainerIdentifier;
using (var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId))
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysTOFetch, out error);
}
var contacts = new List<UserContact>();
foreach (var item in contactList)
{
if (null != item && null != item.EmailAddresses)
{
contacts.Add(new UserContact
{
GivenName = item.GivenName,
FamilyName = item.FamilyName,
EmailId = item.EmailAddresses.Select(m => m.Value.ToString()).ToList()
});
}
}
return contacts;
}
Make sure you include contact attributes you need in KeysToFetch array
Upvotes: 1