3

使用 CNContactStore 获取联系人列表并将完整的联系人列表转换为 VCard,一切都很好,除了我没有得到联系人图像和注释。

   NSMutableArray *contactsArray=[[NSMutableArray alloc] init];
   CNContactStore *store = [[CNContactStore alloc] init];
   [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (!granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
        return;
    }
    NSMutableArray *contacts = [NSMutableArray array];
    NSError *fetchError;

    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[[CNContactVCardSerialization descriptorForRequiredKeys], [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

    BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
        [contacts addObject:contact];
    }];
    if (!success) {
        NSLog(@"error = %@", fetchError);
    }

    for (CNContact *contact in contacts) {
        CNContact *contact1 = contact.mutableCopy;
        [contactsArray addObject:contact1];
    }

    NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];

    vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
    NSLog(@"vcardStr = %@",vcardStr);
  }];
4

1 回答 1

0

来自 CNContact 的联系人资料图片

 if (granted == YES) {
 NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
 NSString *containerId = store.defaultContainerIdentifier;
 NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
 NSError *error;
 NSArray *Contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
 if (error)
 {
    //error
 } 
else 
{    
for (CNContact *contact in Contacts)
{
UIImage *contactProfileImage;
if (contact.imageDataAvailable) 
{
  UIImage * image = [UIImage imageWithData:contact.imageData];
  contactProfileImage = image; 
}
else
{
  contactProfileImage = [UIImage imageNamed:@"icon.png"];
}
}
于 2017-07-05T12:34:11.053 回答