2016-11-21 85 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陣列