在iOS Swift 3中将NSAttributedString转换为HTML [英] NSAttributedString to HTML in iOS Swift 3

查看:52
本文介绍了在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
    }
}

这篇关于在iOS Swift 3中将NSAttributedString转换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆