使用MFMailComposer发送CSV文件

时间:2012-05-20 20:38:45

标签: ios xcode mfmailcomposeviewcontroller

我想使用带有.csv扩展名的NSString(已经制作)创建一个文件,然后使用UIMessage框架通过电子邮件发送它。因此,有人可以向我展示创建文件的代码(带有.csv扩展名和NSString的内容),然后如何将其附加到MFMailComposeViewController。

2 个答案:

答案 0 :(得分:12)

这是将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 课程可以为您提供帮助。

答案 1 :(得分:3)

以下是您创建新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];
}