0
我想將.csv文件附加到電子郵件中,以便用戶可以發送它。此時,我知道該文件實際上是在我在模擬器中工作時創建的(我可以找到並打開它),並且它似乎被附加到創建的電子郵件中。但是,由於我無法從SIM卡發送電子郵件,所以我儘可能地到達那裏。將文件附加到電子郵件 - 收到文件後不存在
在我的iPad上部署,其跡象表明該文件已創建並附加到電子郵件(正確標題爲文件圖標包含在電子郵件正文中)。我可以通過電子郵件發送電子郵件,但收到電子郵件時未附上任何文件。
下面是我使用的創建和寫入文件的代碼:
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"dataFilePath created");
return [documentsDirectory stringByAppendingPathComponent:@"WMDGstats.csv"];
NSLog(@"File path: %@", documentsDirectory);
}
-(void) createCSVFile
{
NSLog(@"Top of createCSVFile");
// [[NSFileManager defaultManager] removeItemAtPath:pngFilePath error:&error];
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]])
{
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(@"File created");
}
...yada, yada data creation
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
[handle truncateFileAtOffset:0];
[handle writeData:[fullString dataUsingEncoding:NSUTF8StringEncoding]];
[self mailCSV];
}
而這裏的我把它附加到電子郵件的方式:
-(void) mailCSV
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:@"Subject"];
[mail setMessageBody:@"message body" isHTML:NO];
[mail setToRecipients:@[@"[email protected]"]];
NSData *WMDGData = [NSData dataWithContentsOfFile:@"WMDGstats.csv"];
[mail addAttachmentData:WMDGData mimeType:@"text.csv" fileName:@"WMDGstats.csv"];
[self presentViewController:mail animated:YES completion:NULL];
}
else
{
NSLog(@"This device cannot send email");
}
}
任何想法?
感謝您的期待!
編輯:
每rmaddy在下面他的評論親切指導下,我提供該文件的完整的文件路徑:
NSData *WMDGData = [NSData dataWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:@"WMDGstats.csv"]];
而且它完美的作品 - 創建,並附加,郵寄文件並收到!
謝謝rmaddy !!!
我不知道這是造成問題,但'text.csv'不是正確的MIME類型。試試'text/csv'。 – bdesham 2014-10-05 15:58:20
您需要在調用'[NSData dataWithContentsOfFile:@「WMDGstats.csv」];'時指定完整路徑,而不僅僅是文件名。很可能,'WMDGData'是'nil',因爲你的路徑無效。 – rmaddy 2014-10-05 16:01:49
是的!!!完美,謝謝@rmaddy!請參閱上面的我的編輯,並請您在評論中回答,以便我可以接受它,並upvote它! – rattletrap99 2014-10-05 16:24:51