我想获取iOS Xamarin中的所有联系人记录。 我用过代码 - > https://developer.xamarin.com/recipes/ios/shared_resources/contacts/find_a_contact/
代码:
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);
}
错误代码:
此错误: Foundation.MonoTouchException:Objective-C异常 抛出。名称:NSInvalidArgumentException原因:+ [CNContact predicateForContactsMatchingName:]:发送到的无法识别的选择器 class 0x1a3e1ec
我已添加[Export("predicateForContactsMatchingName:")]
,但没有帮助。
答案 0 :(得分:1)
“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数组中包含所需的联系人属性