Attach csv to email xcode

大城市里の小女人 提交于 2019-12-01 14:42:26

For anyone else interested in creating and adding a csv to an email using the MessageUI.framework and MFMailComposeViewControllerDelegate, 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];
}

The solution to my own problem was quite simple (if anyone ever happens to come across my post): I replaced the "," by a semicolon so

[csv appendFormat:@"\n%@ ;%@,", key, value];

(don't need the \" since it*'s a string already). It works with excel now but does not display correctly on iPhones/iPads anymore because the field separator there is a ",".

But my problem is solved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!