0

我正在使用下面的代码csv通过电子邮件发送。电子邮件已发送,我在收件箱中收到了,但我没有收到csv附加文件,知道出了什么问题吗?

-(void)generateCSV
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *dirPaths;
NSString *docsDir;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                               NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];

if ([filemgr fileExistsAtPath:[NSString stringWithFormat:@"%@/test.csv", docsDir] ] == NO)
{
    [filemgr createFileAtPath:[NSString stringWithFormat:@"%@/test.csv", docsDir] contents:[@"" dataUsingEncoding: NSUnicodeStringEncoding] attributes: nil];
}

surveyarray = [db retrieveSurvey];

CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:[NSString stringWithFormat:@"%@/test.csv", docsDir] atomic:NO];

NSString *str = [NSString stringWithFormat: @"No, CreatedDate, Question1, Question2, Question3, Comment\n"];
[csvWriter writeField:str];

for(int i = 0; i < surveyarray.count; i++)
{
    survey = [surveyarray objectAtIndex:i];
    NSString *str = [NSString stringWithFormat: @"%d, %@, %@, %@, %@, %@\n", i,  survey.createddate, survey.question1, survey.question2, survey.question3, survey.comment];
    [csvWriter writeField:str];
}

NSMutableString *subject = [[NSMutableString alloc] init];
NSMutableString *emailBody = [[NSMutableString alloc] init];

[subject appendString:@""];

MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

mailer.mailComposeDelegate = self;

[mailer setSubject:subject];

NSArray *toRecipients = [NSArray arrayWithObjects:@"", nil];
[mailer setToRecipients:toRecipients];

NSData *myData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/test.csv", docsDir]];
NSLog(@"%@", myData);

[mailer addAttachmentData:myData mimeType:@"text/csv" fileName:@"test.csv"];

[mailer setMessageBody:emailBody isHTML:NO];

mailer.modalPresentationStyle = UIModalPresentationPageSheet;

[self presentModalViewController:mailer animated:YES];

[mailer release];
[subject release];
[emailBody release];

[csvWriter release];
}

我正在生成csv文件,然后将电子邮件作为附件发送。

我打开邮箱中的电子邮件,它不包含任何附件。

4

5 回答 5

0

根据 NSData 类参考,dataWithContentsOfFile: 给出的路径应该是绝对路径。所以你应该使用

[NSString stringWithFormat:@"%@/test.csv", docsDir]

而不仅仅是@"test.csv"

我敢打赌,目前您的myData值为 nil 或为空。

顺便说一句,我只会使用完全限定的路径/文件名创建一个 NSString 对象,然后重复使用它,而不是创建 3 或 4 次。

于 2012-12-19T10:36:05.347 回答
0

这段代码每次都对我有用!

http://developer.apple.com/library/ios/#samplecode/MailComposer/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008865
于 2012-12-23T08:19:54.470 回答
0

根据我在那里看到的,我会说你忘了.csv在文件名的末尾添加:)

于 2012-12-19T10:28:46.210 回答
-1

尝试替换上面的行

[mailer addAttachmentData:myData mimeType:@"text/csv" fileName:@"test.csv"];
于 2012-12-19T10:34:55.983 回答
-1

finally I solved the problem. The email did attached attachment just the file is empty. This is because the for loop initial with -1 and i change to int i = 0, it works fine now

于 2012-12-20T03:39:03.153 回答