使用Objective-C中的Contacts.Framework导出一个.vcf文件中的所有联系人

时间:2017-01-07 14:37:51

标签: objective-c contacts addressbook vcard vcf

使用I AddressBook.framework我曾经从所有联系人创建Contacts.vcf并将其保存在文档目录中。 这是我以前使用的代码:

ABAddressBookRef addressBook1 = ABAddressBookCreate();
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook1);
long cnt = (unsigned long)[arrayOfAllPeople count];
if (cnt==0) {

    ABAddressBookRequestAccessWithCompletion(addressBook1, nil);

}

if(ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
    ABAddressBookRef addressBook2 = ABAddressBookCreate();


    CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook2);
    CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contacts);


    NSString *vcardString = [[NSString alloc] initWithData:(__bridge NSData *)vcards encoding:NSUTF8StringEncoding];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:@"Contacts.vcf"];
    [vcardString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    CFRelease(addressBook2); }

如何使用Contacts.framework创建包含所有设备联系人的Contacts.vcf文件并将其保存在文档目录中?

2 个答案:

答案 0 :(得分:4)

您可以使用此方法获取.vcf文件中的所有联系人。它返回使用AddressBook.framework获得的相同输出。

- (void)getContacts {
    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);
        }

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

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

答案 1 :(得分:0)

从iOS 9+版本开始,AddressBookUI.framework和Addressbook.framework已弃用。 Apple推出了ContactUI.framework和Contact.framework,并对AddressBookUI.framework和Addressbook.framework进行了改进。在这篇博客中,我们将讨论如何使用这两个新框架并导出VCard。让我们开始从电话联系人那里获取联系人并访问该人的基本信息。

步骤1.创建新的Xcode项目名称ContactDemo并导入Contacts.framework和ContactsUI.framework,如图所示。

Step 1

步骤2.在项目中添加UIButtonUIImageView和3 UILabel s,如图所示:

Step 2

步骤3.在各个视图控制器中创建按钮操作,图像视图和标签的出口:

@property (weak, nonatomic) IBOutlet UIImageView *personImage;
@property (weak, nonatomic) IBOutlet UILabel *personName;
@property (weak, nonatomic) IBOutlet UILabel *emailId;
@property (weak, nonatomic) IBOutlet UILabel *phoneNo;

- (IBAction)selectAction:(id)sender;

步骤4.将代理人CNContactPickerDelegate添加到viewController

步骤5.添加委托方法:

- (void) contactPicker:(CNContactPickerViewController *)picker
didSelectContact:(CNContact *)contact {
[self getContactDetails:contact];
}

此委托方法将以CNContact对象的形式返回联系人,将以本地方法进一步处理

-(void)getContactDetails:(CNContact *)contactObject {

NSLog(@"NAME PREFIX :: %@",contactObject.namePrefix);
NSLog(@"NAME SUFFIX :: %@",contactObject.nameSuffix);
NSLog(@"FAMILY NAME :: %@",contactObject.familyName);
NSLog(@"GIVEN NAME :: %@",contactObject.givenName);
NSLog(@"MIDDLE NAME :: %@",contactObject.middleName);


NSString * fullName = [NSString stringWithFormat:@"%@ %@",contactObject.givenName,contactObject.familyName];
[self.personName setText:fullName];


if(contactObject.imageData) {
NSData * imageData = (NSData *)contactObject.imageData;
UIImage * contactImage = [[UIImage alloc] initWithData:imageData];
[self.personImage setImage:contactImage];
}

NSString * phone = @"";
NSString * userPHONE_NO = @"";
for(CNLabeledValue * phonelabel in contactObject.phoneNumbers) {
CNPhoneNumber * phoneNo = phonelabel.value;
phone = [phoneNo stringValue];
if (phone) {
userPHONE_NO = phone;
}}

NSString * email = @"";
NSString * userEMAIL_ID = @"";
for(CNLabeledValue * emaillabel in contactObject.emailAddresses) {
email = emaillabel.value;
if (email) {
userEMAIL_ID = email;
}}

NSLog(@"PHONE NO :: %@",userPHONE_NO);
NSLog(@"EMAIL ID :: %@",userEMAIL_ID);
[self.emailId setText:userEMAIL_ID];
[self.phoneNo setText:userPHONE_NO];
}

步骤6.创建CNContactPickerViewController类对象并在按钮IBAction方法中注册其委托:

- (IBAction) selectAction:(id)sender {
CNContactPickerViewController *contactPicker = [CNContactPickerViewController new];
contactPicker.delegate = self;
[self presentViewController:contactPicker animated:YES completion:nil];
}

[self presentViewController:contactPicker animated:YES completion:nil];将显示联系人列表的视图。

步骤7.运行项目

A。主视图

Step 7

B中。点击“选择联系人”按钮CNContactPickerViewController将打开,如图所示:

Step 7B

℃。选择一个联系人,视图将被解雇,您将获得该联系人的详细信息,如图所示:

Step 7C

之前我们有写入权限代码来访问联系人,但现在它隐含地授予了访问联系人的权限。有了这个框架,我们还可以生成VCard(VCF)并在其他平台之间共享。以下是创建VCard的步骤。

步骤1.从CNContactPickerViewController中选择联系人,如上所述,您将在代理中获得CNContact个对象。

步骤2.在文档目录中保存联系人。数据以NSData形式存储,以便将联系人转换为NSData 使用代表CNContactVCardSerialization格式的VCard的NSData类。

- (NSString *) saveContactToDocumentDirectory:(CNContact *)contact {

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * VCardPath = [documentsDirectory stringByAppendingString:@"/VCard.vcf"];

NSArray *array = [[NSArray alloc] initWithObjects:contact, nil];

NSError *error;
NSData *data = [CNContactVCardSerialization dataWithContacts:array error:&error];
[data writeToFile:VCardPath atomically:YES];

return VCardPath;
}

CNContactVCardSerialization类方法dataWithContacts:error:接受一组联系对象(CNContact class Object)。

saveContactToDocumentDirectory方法将返回Vcard的文件路径。使用文件路径,您可以在任何地方导出联系人。

来源:Contacts UI, Contacts Framework and create VCard(VCF) in Objective-C