我使用以下方法检索所有联系人
- (void)getAllContacts:(void(^)(NSArray *array))handler
{
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied)
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app prevIoUsly was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:TRUE completion:nil];
return;
}
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted,NSError * _Nullable error) {
// make sure the user granted us access
if (!granted)
{
dispatch_async(dispatch_get_main_queue(),^{
// user didn't grant access;
// so,again,tell user here why app needs permissions in order to do it's job;
// this is dispatched to the main queue because this request Could be running on background thread
});
return;
}
// build array of contacts
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey,CNContactEmailAddressesKey,CNContactBirthdayKey,CNContactimageDataKey,CNContactPhoneNumbersKey,[CNContactFormatter descriptorForrequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact,BOOL *stop) {
[contacts addobject:contact];
}];
if (!success)
{
NSLog(@"error = %@",fetchError);
return;
}
handler((NSArray *)contacts);
}];
}
表格中列出了联系人.现在我试图从“中选择特定的联系方式,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
CNContact *contact = [arrContacts objectAtIndex:indexPath.row];
NSArray *keys = @[CNContactIdentifierKey,[CNContactFormatter descriptorForrequiredKeysForStyle:CNContactFormatterStyleFullName]];
CNContactViewController *contactController = [CNContactViewController viewControllerForContact:contact];
contactController.delegate = self;
contactController.allowsEditing = YES;
contactController.allowsActions = YES;
contactController.displayedPropertyKeys = keys;
[self.navigationController pushViewController:contactController animated:TRUE];
}
但它说
Contact 0x7fc732654530 is missing some of the required key descriptors
如果有人知道,请帮我解决.谢谢.
解决方法
在keysToFetch数组的末尾添加“CNContactViewController.descriptorForrequiredKeys”.
在我这样做之后为我工作.
例:
NSArray *keysToFetch = @[CNContactIdentifierKey,CNContactGivennameKey,CNContactFamilyNameKey,CNContactimageDataAvailableKey,CNContactViewController.descriptorForrequiredKeys];