用MFMailComposer发送电子邮件CSV文件

我想用一个扩展名为.csv的NSString(已经创build)创build一个文件,然后用UIMessage框架给它发邮件。 所以有人可以告诉我创build一个文件(带.csv扩展名和NSString的内容)的代码,然后如何将它附加到MFMailComposeViewController。

这是如何将CSV文件附加到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. 

至于如何生成CSV文件本身,在https://github.com/davedelong/CHCSVParser CHCSVWriter类将帮助你。

以下是您创build新csv的部分,将其保存到文件并将其全部整合在一起。 你知道,如果你是这样的事情

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