oc 导出通讯录 格式为vcf

- (void)getContacts{

NSMutableArray*contactsArray=[[NSMutableArrayalloc]init];

CNContactStore*store = [[CNContactStorealloc]init];

[storerequestAccessForEntityType:CNEntityTypeContactscompletionHandler:^(BOOLgranted,NSError*_Nullableerror) {

if(!granted) {

dispatch_async(dispatch_get_main_queue(), ^{

});

return;

}

NSMutableArray*contacts = [NSMutableArrayarray];

NSError*fetchError;

CNContactFetchRequest*request = [[CNContactFetchRequestalloc]initWithKeysToFetch:@[[CNContactVCardSerializationdescriptorForRequiredKeys], [CNContactFormatterdescriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

BOOLsuccess = [storeenumerateContactsWithFetchRequest:requesterror:&fetchErrorusingBlock:^(CNContact*contact,BOOL*stop) {

[contactsaddObject:contact];

}];

if(!success) {

NSLog(@"error = %@", fetchError);

}

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

CNContactFormatter*formatter = [[CNContactFormatteralloc]init];

for(CNContact*contactincontacts) {

[contactsArrayaddObject:contact];

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

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

}

//NSError *error;

NSData*vcardString =[CNContactVCardSerializationdataWithContacts:contactsArrayerror:&error];

NSString* vcardStr = [[NSStringalloc]initWithData:vcardStringencoding:NSUTF8StringEncoding];

NSLog(@"vcardStr = %@",vcardStr);

NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString*folderPath = [pathsobjectAtIndex:0];

NSString*filePath = [folderPathstringByAppendingPathComponent:@"Contacts.vcf"];

[vcardStrwriteToFile:filePathatomically:YESencoding:NSUTF8StringEncodingerror:nil];

}];

}

你可能感兴趣的:(oc 导出通讯录 格式为vcf)