Frames84
Frames84

Reputation: 177

How to convert NSString HTML markup to plain text NSString?

Been searching the net for an example of how to convert HTML string markup into Plain text.

I get my information from a feed which contains HTML, I then display this information in a Text View. does the UITextView have a property to convert HTML or do I have to do it in code. I tried:

NSString *str = [NSString stringWithCString:self.fullText encoding:NSUTF8StringEndcoding];

but doesn't seem to work. Anyone got any ideas?

Upvotes: 12

Views: 21776

Answers (4)

Madhup Singh Yadav
Madhup Singh Yadav

Reputation: 8114

You can do it by parsing the html by using NSScanner class

- (NSString *)flattenHTML:(NSString *)html {

    NSScanner *theScanner;
    NSString *text = nil;
    theScanner = [NSScanner scannerWithString:html];

    while ([theScanner isAtEnd] == NO) {

        [theScanner scanUpToString:@"<" intoString:NULL] ; 

        [theScanner scanUpToString:@">" intoString:&text] ;

        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    //
    html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    return html;
}

Hope this helps.

Upvotes: 33

Veera Raj
Veera Raj

Reputation: 1562

If you are using UIWebView then it will be easier to parse HTML to text:

fullArticle = [webView stringByEvaluatingJavaScriptFromString:@"document.body.getElementsByTagName('article')[0].innerText;"]; // extract the contents by tag

fullArticle = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerText"]; // extract text inside body part of HTML

Upvotes: 8

dusker
dusker

Reputation: 580

If you need to present the text in read-only fashion, why not use UIWebView?

Upvotes: -1

Mihir Mehta
Mihir Mehta

Reputation: 13833

you can't do it directly i guess.. however you can use NSXML Parser and parse the HTML and retrieve exactly what you want...

Upvotes: -1

Related Questions