Email CSV file with MFMailComposer

本秂侑毒 提交于 2019-12-01 00:58:50

This is how you attach a CSV file to a MFMailComposeViewController:

    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
    mailer.mailComposeDelegate = self;
    [mailer setSubject:@"CSV File"];        
    [mailer addAttachmentData:[NSData dataWithContentsOfFile:@"PathToFile.csv"]
                     mimeType:@"text/csv" 
                     fileName:@"FileName.csv"];
    [self presentModalViewController:mailer animated:YES];

    // Note: PathToFile.csv is the actual path of the file on your iOS device's 
    // file system. FileName.csv is what it should be displayed as in the email. 

As far as how to generate the CSV file itself, the CHCSVWriter class at https://github.com/davedelong/CHCSVParser will help you.

Here are the parts where you create a new csv, save it to file and attach it all in one. You know, if you're in to that sort of thing

NSString *emailTitle = @"My Email Title";
NSString *messageBody = @"Email Body";

MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:@[]];

NSMutableString *csv = [NSMutableString stringWithString:@""];

//add your content to the csv
[csv appendFormat:@"MY DATA YADA YADA"];

NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"MyCSVFileName.csv";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
    [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}

BOOL res = [[csv dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];

if (!res) {
    [[[UIAlertView alloc] initWithTitle:@"Error Creating CSV" message:@"Check your permissions to make sure this app can create files so you may email the app data" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil] show];
}else{
    NSLog(@"Data saved! File path = %@", fileName);
    [mc addAttachmentData:[NSData dataWithContentsOfFile:fileAtPath]
                     mimeType:@"text/csv"
                     fileName:@"MyCSVFileName.csv"];
    [self presentViewController:mc animated:YES completion:nil];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!