2016-11-21 54 views
0

我想获取iOS Xamarin中的所有联系人记录。 我使用的代码 - >https://developer.xamarin.com/recipes/ios/shared_resources/contacts/find_a_contact/如何获取ios中的所有联系人记录xamarin

代码:

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); 
    } 

错误代码:

This Error: Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: +[CNContact predicateForContactsMatchingName:]: unrecognized selector sent to class 0x1a3e1ec

我已经添加[Export("predicateForContactsMatchingName:")],但它并没有帮助。

+0

无法重现的需要。 –

回答

0

“Appleseed”是本示例中使用的搜索术语。看起来像你的不匹配是因为没有任何联系人与谓词匹配。

无论如何,在我自己的实施过程中,我遇到了很多问题。下面是一个完整的解决方案来获取iOS Xamarin中的所有联系人。

第一:允许添加在info.plist中

<key>NSContactsUsageDescription</key> 
<string>This app requires contacts access to function properly.</string> 

二:创建联系人信息

在这个例子模型下面我只加3场

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; } 
    } 
} 

三:读取联系人

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; 
     } 

请确保您有接触的属性你KeysToFetch阵列

相关问题