有没有一种方法可以在Swift中将NSAttributedString转换为HTML?

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

2个回答

3
可以用自己的扩展来包装 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
    }
}

3
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")
}

你可以使用这段代码。这是一个Swift示例。

2
如果我只想获取包含HTML标签的文本,我该怎么做?你有任何想法吗? - Uma Madhavi
我面临的最大问题是,当我使用它时,内容的字体大小会增加,为什么我不知道,但它几乎增加了一倍。 - Mehul Thakkar
1
这不会返回简单的HTML字符串。 - Parth Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接