CNContactPickerViewController获取错误(CNPropertyNotFetchedException) - Objective-C

时间:2016-11-03 14:50:04

标签: objective-c ios9 cncontact

我正在调用联系人选择器视图:

- (void)openContacts {
    CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];

    picker.delegate = self;

    picker.displayedPropertyKeys = @[CNContactGivenNameKey];

    [self presentViewController:picker animated:YES completion:nil];
}

我正在使用此委托方法处理选择:

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
    for (CNContact *contact in contacts) {
        NSLog(@"%@",contact);
        NSString *phone;
        NSString *mobilePhone;

        for (CNLabeledValue *label in contact.phoneNumbers) {
            if ([label.label isEqualToString:CNLabelPhoneNumberMobile] || [label.label isEqualToString:CNLabelPhoneNumberiPhone]) {
                mobilePhone = [label.value stringValue];
            } else if ([label.label isEqualToString:CNLabelPhoneNumberMain]) {
                phone = [label.value stringValue];
            }
        }
    }
}

NSLog输出以下内容进行联系:<CNContact: 0x78e56e50: identifier=1861C9BD-143B-4E93-8475-F9079F5D6192, givenName=Kate, familyName=Bell, organizationName=Creative Consulting, phoneNumbers=(not fetched), emailAddresses=(not fetched), postalAddresses=(not fetched)>

这只发生在模拟器和iOS9 iPad上。我的iOS10 iPhone没有出错。

1 个答案:

答案 0 :(得分:0)

你应该首先征得许可。然后你可以显示选择器。

CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error)
 {
         CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
         picker.delegate = self;
         picker.displayedPropertyKeys = @[CNContactGivenNameKey];
         [self presentViewController:picker animated:YES completion:nil];
 }];

在这种情况下,您将始终显示选择器,而不依赖于用户的选择。所以你应该查看属性可用性:

if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized)
    {

    }