iphone - 在 Objective-C 中创建 vCard?

标签 iphone objective-c xcode

我想在 objective-c 中创建 vCard ( http://en.wikipedia.org/wiki/VCard )?

你能给我举个例子来说明如何做到这一点吗? 还有一个问题我可以在短信中附加电子名片吗?

谢谢

最佳答案

// 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];

}];

}

关于iphone - 在 Objective-C 中创建 vCard?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8224463/

相关文章:

iphone - UIView旋转然后移动

iphone - canSendText 返回 false

ios - 错误: failed to launch '/private/var/containers/Bundle/Application/problem still not solved

ios - 如何在 Xcode 10 中设置对象的高度和宽度?如果我们设置值,它表示固定约束可能会导致裁剪

iphone - 向表中插入数据时出现问题

ios - 在 iPhone App 中使用 AVSystemController

iphone - 如何用 CGPathAddCurveToPoint 创建一个完美的半圆?

objective-c - 如何分析opencv的cvMatchTemplate返回的min max loc?

objective-c - 在不重新编译的情况下从静态 lib(.a) 中删除方法调用

ios - iOS 上带有 Storyboard 的 TableView 导航栏中的返回、编辑和添加按钮