有没有办法在swift中将NSAttributedString转换为HTML?

时间:2015-09-25 13:57:54

标签: html ios string swift nsattributedstring

我想将NSAttributedString转换为HTML字符串。我一直在寻找如何解决它,但我还没有结果。

知道我该怎么做?

2 个答案:

答案 0 :(得分:2)

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

你可以使用这段代码。例如,快速的例子

答案 1 :(得分:0)

可以包装在NSAttributedString自己的扩展名中

// swift 5.2 

import Foundation

extension NSAttributedString {
    func toHtml() -> String? {
        let documentAttributes = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
        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 {
            print("error creating HTML from Attributed String")
        }
        return nil
    }
}