【问题标题】:Email attachment has no content电子邮件附件没有内容
【发布时间】:2015-02-19 08:25:50
【问题描述】:

我正在尝试在我的应用中通过电子邮件发送用户数据的 CSV 副本,并且尝试了几种不同的方法。它在邮件视图控制器中显示为“Backup.csv”,但是当我通过电子邮件发送它时,当我收到电子邮件时没有内容。这可能是什么原因造成的?

-(void)backupDatabase {
    NSString *CSVstring = [NSString string];
    for (SELVendor *vendor in [[SELVendorStore store] allVendors]) {
        [CSVstring stringByAppendingString:[NSString stringWithFormat:@"\"vendor\",\"%@\",\"%@\",\"%@\",\"%@\",%i\n",vendor.name, vendor.phone, vendor.email, vendor.vendorID, vendor.placeOrderByEmail]];
    }

    // Create CSV file
    NSArray *directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [directory[0] stringByAppendingPathComponent:@"databaseBackup"];
    NSError *error;
    [CSVstring writeToFile:filePath atomically:false encoding:NSStringEncodingConversionAllowLossy error:&error];
//    [[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil];
//    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
//    [fileHandle seekToEndOfFile];
//    [fileHandle writeData:[CSVstring dataUsingEncoding:NSUTF8StringEncoding]];

    // Setup email and attach CSV file
    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
    mailer.mailComposeDelegate = self;
    [mailer setSubject:@"Inventory App CSV Backup"];
    [mailer addAttachmentData:[NSData dataWithContentsOfFile:filePath] mimeType:@"text/csv"  fileName:@"Backup.csv"];
    [self presentViewController:mailer animated:true completion:nil];
}

【问题讨论】:

标签: ios email csv mfmailcomposeviewcontroller


【解决方案1】:

NSStringEncodingConversionAllowLossy 不是有效的字符串编码。
您基本上使用的是NSASCIIStringEncoding,因为您使用了错误的枚举。因此,如果您的字符串不是严格的 ASCII,则无法将其转换为 NSData,也不会写入磁盘。

首先检查文件是否可以写入磁盘。即

if (![CSVstring writeToFile:filePath atomically:false encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"Could not write file %@", error);
} 
else {
    MFMailComposeViewController ...
}

编辑:并且您不会将 CSV 行添加到您的字符串中。所以你会创建一个空字符串。

[CSVstring stringByAppendingString:...]; 创建一个新字符串。但是您不会将该字符串分配给任何东西。

所以把那部分改成:

NSString *CSVstring = [NSString string];
for (SELVendor *vendor in [[SELVendorStore store] allVendors]) {
    CSVstring = [CSVstring stringByAppendingString:[NSString stringWithFormat:@"\"vendor\",\"%@\",\"%@\",\"%@\",\"%@\",%i\n",vendor.name, vendor.phone, vendor.email, vendor.vendorID, vendor.placeOrderByEmail]];
}

或到

NSMutableString *CSVstring = [NSMutableString string];
for (SELVendor *vendor in [[SELVendorStore store] allVendors]) {
    [CSVstring appendString:[NSString stringWithFormat:@"\"vendor\",\"%@\",\"%@\",\"%@\",\"%@\",%i\n",vendor.name, vendor.phone, vendor.email, vendor.vendorID, vendor.placeOrderByEmail]];
}

【讨论】:

  • 我自己也注意到了这一点,并正在写这篇文章。尴尬!
猜你喜欢
  • 1970-01-01
  • 2013-11-03
  • 2014-05-29
  • 2015-09-25
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
相关资源
最近更新 更多