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.
Using of NSHTMLTextDocumentType is slow and it is hard to control styles. I suggest you to try my library which is called Atributika. It has its own very fast HTML parser. Also you can have any tag names and define any style for them.
Example:
You can find it here https://github.com/psharanda/Atributika
Swift 3:
Try this:
And for using:
The only solution you have right now is to parse the HTML, build up some nodes with given point/font/etc attributes, then combine them together into an NSAttributedString. It's a lot of work, but if done correctly, can be reusable in the future.
This is a
String
extension written in Swift to return a HTML string asNSAttributedString
.To use,
In the above, I have purposely added a unicode \u2022 to show that it renders unicode correctly.
A trivial: The default encoding that
NSAttributedString
uses isNSUTF16StringEncoding
(not UTF8!).The above solution is correct.
But the app wioll crash if you are running it on ios 8.1,2 or 3.
To avoid the crash what you can do is : run this in a queue. So that it always be on main thread.
Helpful Extensions
Inspired by this thread, a pod, and Erica Sadun's ObjC example in iOS Gourmet Cookbook p.80, I wrote an extension on
String
and onNSAttributedString
to go back and forth between HTML plain-strings and NSAttributedStrings and vice versa -- on GitHub here, which I have found helpful.The signatures are (again, full code in a Gist, link above):