how to add .vcf file as attachment in application

2020-06-04 05:01发布

问题:

In my app I want to add .vcf file as attachment in MFMailComposeViewController.

回答1:

The documentation for MFMailComposeViewController shows that its addAttachmentData:mimeType:fileName: instance method is the way to go:

- (void)addAttachmentData:(NSData*)attachment mimeType:(NSString*)mimeType fileName:(NSString*)filename

The attachment is the actual vcf file loaded or transformed into NSData.

The mimeType for a vcf is @"text/x-vcard".

The fileName is whatever you want to call it, though you should uses the .vcf extension to ensure that email programs will understand it.



回答2:

Use the below code to create a vcf file and save it in directory.

ABAddressBookRef addressBook = ABAddressBookCreate();

//-------------------Creating and saving vcf --------------------------------
CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contacts);
NSString *vcardString = [[NSString alloc] initWithData:(NSData *)vcards encoding:NSUTF8StringEncoding];
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
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];
NSLog(@"Documents directory: %@",[fileMgr contentsOfDirectoryAtPath: folderPath error:&error]);
if (addressBook) {
    CFRelease(addressBook);
}