Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to create vcard of contacts using contact framework

I am using this code to export contact from ios phonebook to .vcf file. I have used this code for the task. But vcardString is always returning nil. Please help me to solve this issue.

NSMutableArray *contacts=[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:@[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

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

    // you can now do something with the list of contacts, for example, to show the names

    CNContactFormatter *formatter = [[CNContactFormatter alloc] init];

    for (CNContact *contact in contacts) {

        [contactsArray addObject:contact];
        // NSString *string = [formatter stringFromContact:contact];

        //NSLog(@"contact = %@", string);
    }

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

    NSLog(@"vcardString = %@",vcardString);
}];
like image 940
Vijay Bisht Avatar asked Oct 18 '22 17:10

Vijay Bisht


1 Answers

Change this line:

CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[[CNContactVCardSerialization descriptorForRequiredKeys]]

This fetches all required info for creating a vCard.

like image 190
mafellows Avatar answered Oct 21 '22 06:10

mafellows