Wondering if there is an easy way to do a simple HTML escape/unescape in Objective C. What I want is something like this psuedo code:
NSString *string = @\"
Here's a solution that neutralizes all characters (by making them all HTML encoded entities for their unicode value)... Used this for my need (making sure a string that came from the user but was placed inside of a webview couldn't have any XSS attacks):
Interface:
@interface NSString (escape)
- (NSString*)stringByEncodingHTMLEntities;
@end
Implementation:
@implementation NSString (escape)
- (NSString*)stringByEncodingHTMLEntities {
// Rather then mapping each individual entity and checking if it needs to be replaced, we simply replace every character with the hex entity
NSMutableString *resultString = [NSMutableString string];
for(int pos = 0; pos<[self length]; pos++)
[resultString appendFormat:@"%x;",[self characterAtIndex:pos]];
return [NSString stringWithString:resultString];
}
@end
Usage Example:
UIWebView *webView = [[UIWebView alloc] init];
NSString *userInput = @"";
NSString *safeInput = [userInput stringByEncodingHTMLEntities];
[webView loadHTMLString:safeInput baseURL:nil];
Your mileage will vary.