Swift: From HTML to NSAttributedString and Back Again (iOS 9.2.1, Xcode 7.2)


I wrote a post about this ages ago, since when the method I used was deprecated in iOS 9. So here's an update on the code, this time in Swift.

HTML to NSAttributedString

if let htmlURL = NSBundle.mainBundle().URLForResource("page", withExtension: "html"),
   data = NSData(contentsOfURL: htmlURL) {
       do {
           let attrStr = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
                print(attrStr)
       }
       catch {
           print("error creating attributed string")
       }
}
Here an NSURL of a local file is used to generate NSData and then this is converted into a NSAttributedString. What we should no longer do (due to deprecation) is initialise a NSAttributedString from a fileURL directly.

NSAttributedString to HTML

While on this topic it's worth noting how to turn a NSAttributedString into HTML (Obj-C source, StackOverflow):
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")
}

Conclusion

As I wrote in the earlier post, this technique is not confined to HTML. By changing NSHTMLTextDocumentType to one of the other document types you can work with RTF, RTFD and Plain Text.


Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment