在iOS Swift 3中将NSAttributedString转换为HTML

在iOS Swift 3中将NSAttributedString转换为HTML

问题描述:

我进行了很多搜索,但只能找到纯文本格式的HTML,反之则不然,我的应用程序中有电子邮件实现,因此需要将电子邮件内容作为HTML发送到后端.

I have searched a lot but can only find HTML to plain text, not the other way around, I have email implementation in my app, thus need to send the content of email as HTML to the backend.

我有丰富的文本,其中包括粗体,斜体,有序/无序列表,带下划线的单词.

Edit 1: I have rich text that includes bold, italic, ordered/unordered list, underlined words.

如果您想将 NSAttributedString 转换为 String ,这是您要寻找的扩展方法.只需调用 yourAttributtedString.htmlString()并将其打印出来即可.

If you are looking to convert NSAttributedString to String, here is the extension method you are looking for. Simply call yourAttributtedString.htmlString() and print it out.

extension NSAttributedString {
    func htmlString() -> String? {
        let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        do {
            let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
            if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
                return htmlString
            }
        }
        catch {}
        return nil
    }
}