带有归属字符串的Email Composer

时间:2016-03-07 12:33:39

标签: ios swift email nsattributedstring

如何通过电子邮件发送属性字符串?

mailComposerVC.setMessageBody(textView.attributedString, isHTML: false)

3 个答案:

答案 0 :(得分:5)

您已将Attributed字符串转换为HTML字符串。使用以下代码生成html字符串。

        do {
        let data = try string.dataFromRange(NSMakeRange(0, string.length), documentAttributes: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType])
        let htmlString = String(data: data, encoding: NSUTF8StringEncoding)
    }catch {

    }

使用生成的html字符串作为

mailComposerVC.setMessageBody(htmlString, isHTML: true)

答案 1 :(得分:2)

谢谢大家,这就是它的完成方式:

    var cookedString : String!
    let attributeStrung = myTextView.attributedText

    let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do
    {
        let htmlData = try attributeStrung.dataFromRange(NSMakeRange(0, attributeStrung.length), documentAttributes: documentAttributes)
        if let htmlString = String(data: htmlData, encoding: NSUTF8StringEncoding)
        {
            cookedString = htmlString
        }
    }
    catch
    {
        print("error creating HTML from Attributed String")
    }

    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self
    mailComposerVC.setMessageBody(cookedString, isHTML: true)

答案 2 :(得分:0)

已更新为Swift 5 Xcode 12.1

var cookedString : String!
let attributeString = myTextView.attributedText

    let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
        do
        {
            let htmlData = try attributeString!.data(from: NSMakeRange(0, attributeStrung!.length), documentAttributes: documentAttributes)
            if let htmlString = String(data: htmlData, encoding: String.Encoding.utf8)
            {
                cookedString = htmlString
            }
        }
        catch
        {
            print("error creating HTML from Attributed String")
        } let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setMessageBody(cookedString, isHTML: true)