user784625
user784625

Reputation: 1938

create vCard in objective-c?

I want to create a vCard ( http://en.wikipedia.org/wiki/VCard ) in objective c?

can u give me example of how doing that? and another question can I attach the vCard in sms?

Thanks

Upvotes: 3

Views: 1599

Answers (2)

Ramani Hitesh
Ramani Hitesh

Reputation: 214

// Create vcd file all contacts
- (void)CreateVCardfile {
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);
    }



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

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

    NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];
    NSString* vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
    NSLog(@"vcardStr = %@",vcardStr);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folderPath = [paths objectAtIndex:0];

    NSString *filePath = [folderPath stringByAppendingPathComponent:@"Contacts.vcf"];
    [vcardStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    NSArray *objectsToShare = @[fileUrl];

    UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    [self presentViewController:controller animated:YES completion:nil];

}];

}

Upvotes: 1

Monolo
Monolo

Reputation: 18253

The card format is relatively straight-forward in a pure text file. There is a good overview here: http://softwareas.com/vcard-for-developers

You should be able to just construct the file yourself.

Upvotes: 0

Related Questions