Reputation: 177
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
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
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
Reputation: 580
If you need to present the text in read-only fashion, why not use UIWebView?
Upvotes: -1
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