I got a working csv attachment to an email view. The problem is, that when I open the csv on the iPhone it displays the file really nice into separate columns. But if I open
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.
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];
}