Convert attributed text to HTML in Swift 4

杀马特。学长 韩版系。学妹 提交于 2019-12-06 23:53:50

问题


I am trying to convert attributed text to HTML in Swift 4 so that it can be stored in Firebase/Firestore and synced across different devices/platforms. I have read every article I can find on Stackoverflow including Convert attributed string, to, "simple" tagged html, Convert attributed text to HTML and this blog article: http://sketchytech.blogspot.com/2016/02/swift-from-html-to-nsattributedtext-and.html. I am finding that Swift 4.x throws an unresolved identifier error for NSDocumentTypeDocumentAttribute and NSHTMLTextDocumentType in the various code examples there are (example below). These errors are not thrown in Swift 3.x. Xcode suggests that I might mean to use NSDocumentTypeDocumentOption but does not offer a fix and I am not sure if that is what I want or how to use it if it is.

let myAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.green ]
let attrString = NSAttributedString(string: "Hello.", attributes: myAttributes)
let x = attrString
var resultHtmlText = ""
do {

    let r = NSRange(location: 0, length: x.length)
    let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

    let d = try x.data(from: r, documentAttributes: att)

    if let h = String(data: d, encoding: .utf8) {
        resultHtmlText = h
    }
}
catch {
    print("utterly failed to convert to html!!! \n>\(x)<\n")
}
print(resultHtmlText)

Thanks for your help


回答1:


For Swift 4.x, the line:

let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

should be:

let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]


来源:https://stackoverflow.com/questions/50126120/convert-attributed-text-to-html-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!