Wednesday, 23 April 2014

Display HTML in NSAttributedString in iOS7

iOS7 has really added some best things like displaying HTML in NSAttributedString.
Suppose in a case you want to display some HTML in your UITextView from any website.
Just pass the HTML to NSAttributedString and set this attributed string to the UITextView and that's it, you are done.

In below snippet i have passed the html string from my blog site to NSAttributedString and this NSAttributedString is set to UITextView.
Now the html from my blog site will be displayed in the UITextView along with clickable links.

      NSString *strHtml = [NSString stringWithContentsOfURL:[NSURL   URLWithString:@"http://objectivecwithsuraj.blogspot.in/"] encoding:NSUTF8StringEncoding error:nil];
    
    NSAttributedString *attrStrWithHtml = [[NSAttributedString alloc] 
                   initWithData:[strHtml dataUsingEncoding:NSUTF8StringEncoding]
                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                               NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                   documentAttributes:nil error:nil];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:self.view.frame];
    [textView setAttributedText: attrStrWithHtml];
    [textView setDataDetectorTypes:UIDataDetectorTypeLink];
    [textView setEditable:NO];
    [self.view addSubview:textView];

No comments:

Post a Comment