Creating an NSAttributedString from HTML (or RTF) in iOS 7 (Xcode) - Updated for Swift


Following additions to the iOS 7 NSAttributedString class it is now possible to create attributed strings using HTML.

For example:

NSURL *htmlString = [[NSBundle mainBundle] URLForResource: @"helloworld" withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc]   initWithFileURL:htmlString options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
// Instantiate UITextView object
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20,20,self.view.frame.size.width,self.view.frame.size.height)];
textView.attributedText=stringWithHTMLAttributes;
[self.view addSubview:textView];

Two things to note here: (1) this is a rough and ready use of UITextView - see this earlier post for a better implementation (2) you'll need to save an accompanying file called 'helloworld.html' for this to work.

Here is the helloworld.html file:

<html><p>Hello<i>World</i></p></html>

As well as HTML you can use RTF and RTFD files to create attributed strings, using NSRTFTextDocumentType and NSRTFDTextDocumentType respectively in place of NSHTMLTextDocumentType.

Finally, you must take account of the following notes from Apple: "Calling [this method] from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import."

This warning from Apple does not mean that you can't use CSS, in fact you can transform HTML files with linked CSS files into NSAttributedStrings, opening the door to replacing the use of UIWebView in eBook apps with the use of UITextViews.

Swift (update)

Having responded to a StackOverflow post on how to create an NSAttributedString from an RTF file, I thought it worth adding the code here:
import UIKit
import Foundation

class ViewController: UIViewController {

    @IBOutlet var textView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) {

            let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)
            textView.attributedText = attributedString
            
        }


    }

}
Altering the code for HTML, I'll leave for you as a learning exercise.


Endorse on Coderwall

Comments

  1. how to remove underline and changing fornt styles of html text which is coming from server.

    ReplyDelete
    Replies
    1. You either need to change/override the css going in or you need to alter the attributed string afterwards.

      Delete

Post a Comment