I am using a instance of UIWebView
to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the UIWebView
I want to display it using Core Text
with a NSAttributedString
.
I am able to create and draw the NSAttributedString
but I am unsure how I can convert and map the HTML into the attributed string.
I understand that under Mac OS X NSAttributedString
has a initWithHTML:
method but this was a Mac only addition and is not available for iOS.
I also know that there is a similar question to this but it had no answers, I though I would try again and see whether anyone has created a way to do this and if so, if they could share it.
In iOS 7, UIKit added an initWithData:options:documentAttributes:error: method which can initialize an NSAtttributedString using HTML, eg:
In Swift:
Swift 4
Usage
Swift 3.0 Xcode 8 Version
Creating an NSAttributedString from HTML must be done on the main thread!
Update: It turns out that NSAttributedString HTML rendering depends on WebKit under the hood, and must be run on the main thread or it will occasionally crash the app with a SIGTRAP.
New Relic crash log:
Below is an updated thread-safe Swift 2 String extension:
Usage:
Output:
Swift initializer extension on NSAttributedString
My inclination was to add this as an extension to
NSAttributedString
rather thanString
. I tried it as a static extension and an initializer. I prefer the initializer which is what I've included below.Swift 4
Swift 3
Example
There is a work-in-progress open source addition to NSAttributedString by Oliver Drobnik at Github. It uses NSScanner for HTML parsing.