8

How can I encode this url to be displayed in a UIWebview:

http://de.wikipedia.org/?search=Bevölkerungsentwicklung

I tried:

-stringByAddingPercentEscapesUsingEncoding:NSUnicodeStringEncoding
-stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding

and

CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                        (CFStringRef)mobileUrl,
                                        NULL,
                                        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                        kCFStringEncodingUTF8);

thanks

joerg

Cory Kendall
  • 7,195
  • 8
  • 37
  • 64
Joerg
  • 105
  • 2
  • 6

3 Answers3

8

Encode just the search part of the URL string:

// searchString is the unescaped search string, e.g., "Bevölkerungsentwicklung"

NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:@"http://de.wikipedia.org/?search=%@", encodedSearchString];
NSURL *url = [NSURL URLWithString:urlString];

(Note as well that NSUTF8StringEncoding is the encoding used.)

Wevah
  • 28,182
  • 7
  • 83
  • 72
  • 1
    ok this could be an approach but I'm not sure the url will always look like that. Could also be: http://de.wikipedia.org/wiki/Bevölkerungsentwicklung – Joerg Nov 11 '10 at 14:55
  • @Joerg: Sorry; I assumed the search term was user-input. :S – Wevah Nov 11 '10 at 15:55
  • `stringByAddingPercentEscapesUsingEncoding` is deprecated: Use `stringByAddingPercentEncodingWithAllowedCharacters(_:)` instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid. – Ryan R Dec 06 '15 at 08:22
  • That method didn't exist when this question was answered, but that's now correct. – Wevah Dec 06 '15 at 08:46
2

Just use below sample code;


NSString *urlstring = [NSString stringWithFormat:@"http://de.wikipedia.org/?search=%@", searchString];
NSString *encodedString = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedString];
jfalexvijay
  • 3,681
  • 7
  • 42
  • 68
  • 1
    hm yes but I'm looking more for a solution to encode any url. it also could be: http://de.wikipedia.org/wiki/Bevölkerungsentwicklung – Joerg Nov 11 '10 at 14:57
1

I found also that for some North European characters, NSISOLatin1StringEncoding fits better. This one gives me a better result

- (void) testEncoding {
    NSString * urlString = @"http://example/path/fileName_blå.pdf";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
    NSURL * url = [NSURL URLWithString:urlString];
    NSLog(@"URL: %@", url);
}
karim
  • 15,408
  • 7
  • 58
  • 96