Modify Images of NSAttributeString Loaded From HTML in ease


div>Sometime we may want to load a html file and show it straightly on textview,
fast and convenient.
Also we might want to modify the images that automatically  load from the tags (resize the image, filtering...).
Some may suggest you to use a html parser and set the attributes manually, but if we have a easier way to achieve, why the hell would I want to import an extra framework and increase workloads?
So, how?

var attrString = NSAttributeString(...)
var mutableAttrString = NSMutableAttributeString(attrString)

The shiny little stone:

  attrString.enumerateAttribute(NSAttachmentAttributeName, inRange: NSMakeRange(0, attrString.length), options: .LongestEffectiveRangeNotRequired) { (attrObj, currentRange, flag) -&gt; () in if let attachment = attrObj as? NSTextAttachment, let file = attachment.fileWrapper{ // Just for showing, use &quot;guard&quot; / &quot;if let&quot; to bind the optional value in real word! let image = CIImage(data: file.regularFileContents!)! // You should know you can use another filter or any other things you like here let filter = CIFilter(name: &quot;CIGausianBlur&quot;, withInputParameters: [&quot;inputImage&quot;:image])! let filteredCI = filter.outputImage! let cg = CIContext().createCGImage(filteredCI, fromRect: filteredCI.extent) let filteredImage = UIImage(CGImage: cg) let attach = NSTextAttachment() attach.image = filteredImage let attrs = NSAttributedString(attachment: attach) mutableAttrString.replaceCharactersInRange(r, withAttributedString: attrs) } }

First thing first, initiate a NSAttributeString we will work on:
Then make a mutable copy of it:

So we can separate the parsing and modifying objects, to keep our process safely.

Then we are done?
Find the attributes of NSTextAttachment by enumerate the attrString, those which store the images load from tags.
After we found those attachments, we can:
modify the image files and assemble them back in form of new NSTextAttachment objects
associate them with newly created NSAttributeString
replace the mutableAttrString at the current range with the attributeString we create.
The codes:
Now, the attribute string with images modified is ready to use.
Original post from my previous site:

Subscribe to

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.