0

I need to save a HTML page in my app, and when characters like "€" are found, the saved file displays them wrong. I tried several encodings but none solves this, is there any solution? I have also tried to replace the characters for the HTML name, but it still doesn't work. Here's my code:

 NSString *HTML = [web stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML;"];

    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", [path objectAtIndex:0],@"code.html"];

    int enc_arr[] = {
        NSISOLatin1StringEncoding,      // ESP
        NSUTF8StringEncoding,           // UTF-8
        NSShiftJISStringEncoding,       // Shift_JIS
        NSJapaneseEUCStringEncoding,    // EUC-JP
        NSISO2022JPStringEncoding,      // JIS
        NSASCIIStringEncoding           // ASCII
    };

    NSData *urlData= nil;

    for (int i=0; i<6; i++) {
        urlData = [HTML dataUsingEncoding:enc_arr[i]];
        if (urlData!=nil) {
            break;
        }
    }

    [urlData writeToFile:filePath atomically:YES];
Sylphos
  • 156
  • 1
  • 11

2 Answers2

0

See these methods of NSString:

- (NSStringEncoding)smallestEncoding
- (NSStringEncoding)fastestEncoding

or just use method below with flag set to YES :

- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag

but with this one you can loose some characters.

lupatus
  • 4,208
  • 17
  • 19
  • The 2 first methods keep the format, but lose the CSS and misplace all the content. The other displays the characters like "?" so it doesn't work either :( – Sylphos Feb 06 '13 at 12:40
0

Ok I finally did it, it's not the best way but the only one that worked for me and without using external libraries:

-(NSString*)escapeHTML:(NSString*)code{

    NSMutableArray *maExceptions = [[NSMutableArray alloc] initWithObjects: @"Œ", @"œ", @"Š", @"š", @"Ÿ", @"ƒ", @"‘", @"’", @"‚", @"“", @"”", @"„", @"†", @"‡", @"•", @"…", @"‰", @"€", @"™", nil];

    for (int i=0; i<[maExceptions count]; i++) {
        code = [code stringByReplacingOccurrencesOfString:[maExceptions objectAtIndex:i] withString:[NSString stringWithFormat:@"&#x%x;",[[maExceptions objectAtIndex:i] characterAtIndex:0]]];

    }

    return code;
}
Sylphos
  • 156
  • 1
  • 11