Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert attributed text to HTML in Swift 4

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

like image 600
Steve Robertson Avatar asked May 02 '18 01:05

Steve Robertson


1 Answers

For Swift 4.x, the line:

let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

should be:

let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
like image 157
rmaddy Avatar answered Nov 06 '22 00:11

rmaddy