我想将NSAttributedString转换为HTML字符串。我一直在搜索如何解决这个问题,但目前还没有结果。
有任何想法如何做到这一点吗?
有任何想法如何做到这一点吗?
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
}
}
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")
}