嗨,我将示例代码用于创建 CSV 文件并将其附加到邮件中,但请确保您必须添加 MessageUI.Framework 并导入其相关标头“MessageUI/MessageUI.h”“MessageUI/MFMailComposeViewController.h”和 deligate“MFMailComposeViewControllerDelegate”.. .我希望这对其他人有用
- (void)viewDidLoad {
arrCsv=[[NSArray alloc]initWithObjects:@"Hello",@"Hi",@"traun",@"fine",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/try.csv", documentsDirectory];
[[arrCsv componentsJoinedByString:@","] writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
-(ibAction)btnMail {
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
NSString *Path = [docDir stringByAppendingString:@"/CSVFile.csv"];
NSData *csvData = [NSData dataWithContentsOfFile:Path];
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"For csv file..."];
[controller setMessageBody:@"...csv file is hear.." isHTML:NO];
[controller addAttachmentData:csvData mimeType:@"text/csv" fileName:@"CSVFile.csv"];
[self presentModalViewController:controller animated:YES];
[controller release];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{ message.hidden = NO;
switch (result)
{
case MFMailComposeResultCancelled:
message.text = @"Result: canceled";
break;
case MFMailComposeResultSaved:
message.text = @"Result: saved";
break;
case MFMailComposeResultSent:
message.text = @"Result: sent";
break;
case MFMailComposeResultFailed:
message.text = @"Result: failed";
break;
default:
message.text = @"Result: not sent";
break;
}
[self dismissModalViewControllerAnimated:YES];
}