Xamarin Forms iOS中的权限联系人

时间:2019-01-18 04:07:58

标签: xamarin

当我尝试访问用户联系人以获取所有联系人时遇到错误显示:初始屏幕隐藏权限对话框。 有人遇到过这个错误吗? 界面:

公共接口IUserContactsService {

    List<PhoneContactInfo> GetAllPhoneContacts(IEnumerable<int> filterIds = null);
}

UserContactService.cs:

[assembly: Dependency(typeof(UserContactService))]
namespace Test.iOS
{
    public class PhoneContact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }

    public string Name { get => $"{FirstName} {LastName}"; }

}

public class UserContactService : IUserContactsService
{
    string phoneNumber(string number)
    {
        string callNumber = number;
        int i = 0;
        while (i < callNumber.Length)
        {
            if (callNumber[i] == ' ' || callNumber[i] == 160 || callNumber[i] == '-')
                callNumber = callNumber.Remove(i, 1);
            else
                i++;
        }
        return callNumber;
    }

    public List<PhoneContactInfo> GetAllPhoneContacts(IEnumerable<int> filterIds = null)
    {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<PhoneContactInfo>();

        foreach (var item in contactList)
        {
            if (null != item && null != item.EmailAddresses)
            {
                contacts.Add(new PhoneContactInfo
                {
                    contactName = item.GivenName,
                    contactNumber = item.PhoneNumbers.ToString()
                });
            }
        }
        return contacts;
    }

}

1 个答案:

答案 0 :(得分:0)

这是我的解决方法:

public List<PhoneContactInfo> GetAllPhoneContacts (IEnumerable<int> filterIds = null)
{
     // if the app was not authorized then we need to ask permission
     if (ABAddressBook.GetAuthorizationStatus() == ABAuthorizationStatus.Authorized)
      {
          GetContacts();
      }
     else Console.WriteLine("Error");
}