如何正确添加带有电子邮件的附件,特别是 IOS 中的 RTF



我正在做一个项目,该项目具有编辑UITextView中的数据的功能,然后以RTF文件格式通过电子邮件发送该UITextView中的文本。我让一切正常,甚至能够附加数据并通过电子邮件发送。当我尝试下载文件并在计算机上打开它时,问题就出现了,它说"无法打开文档"。但是,当我使用Gmail预览时,我可以看到文本在文件中。

所以我想知道我的代码中是否缺少"完成"RTF 文件的设置或选项?或者如果有比我做的方式更合适的方法。这是我正在做的事情:

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"EMAIL TEST"];
// Fill out the email body text
NSString *emailBody = @"Send RTF";
[picker setMessageBody:emailBody isHTML:NO];
NSData *dataString = [[myTextView text] dataUsingEncoding:NSUTF8StringEncoding];
[picker addAttachmentData:dataString mimeType:@"text/rtf" fileName:@"rtfFileName"];
[self presentViewController:picker animated:YES completion:NULL];

我知道我可以使用 mimeType "text/plain",它会创建一个文本文件,当我通过电子邮件将其发送给自己时,我可以打开该文件。但是我想要一个RTF文件。感谢您的查看和回复!

您实际上没有任何 RTF 可以附加到电子邮件中。文本视图的 text 属性只是纯文本。

您需要将文本视图的attributedText转换为 RTF。这可以按如下方式完成:

NSAttributedString *attrStr = myTextView.attributedText;
NSError *error = nil
NSData *data = [attrStr dataFromRange: NSMakeRange(location: 0, length: attrStr.length]) documentAttributes:@{ NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType } error: &error];
if (data) {
    [picker addAttachmentData:data mimeType:@"text/rtf" fileName:@"rtfFileName"];
} else {
    NSLog(@"Error: %@", error);
}

最新更新