NSString for HTML

I show NSString in UIWebview to show text with custom emoticons (images), but I have problems because UIWebview cannot detect special characters like \ n, \ r, \ t, whitespaces and amp ;, <,> and many other lines. How to convert NSString string to HTML for loading in UIWebView?

+5
source share
4 answers

There is no built-in solution for this. You must encode HTML objects. There is an open source project called NSString-HTML that can suit your needs.

There is also a good NSString category here , which is based on the Google Toolbox .

+3
source

There is actually a built-in solution for this ... In NSAttributedString. Below is the category for NSString, which simplifies:

@interface NSString (HTMLString)
- (NSString *)HTMLString;
@end

@implementation NSString (HTMLString)
- (NSString *)HTMLString {
    NSDictionary * const exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSAttributedString *attributed = [[NSAttributedString alloc] initWithString:self];
    NSData *htmlData = [attributed dataFromRange:NSMakeRange(0, attributed.length) documentAttributes:exportParams error:nil];
    return [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
}
@end
+1
source

Have you tried converting an HTML string to UTF8 format and then loading it into a web view?

[webView loadData:[html dataUsingEncoding:NSUTF8StringEncoding]
                     MIMEType:@\"text/html\"
             textEncodingName:@\"UTF-8\"
                      baseURL:nil];
0
source

You are looking for an ICU transformation. This functionality is wrapped in the CFString API function CFStringTransform () Using the Any-Hex conversion option You can optimize by creating an NSCharacterSet only for glyphs that NEED should be escaped.

0
source

All Articles