NSURL with special characters
Asked Answered
R

3

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

Resile answered 10/11, 2010 at 15:7 Comment(0)
T
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.)

Titleholder answered 10/11, 2010 at 15:38 Comment(4)
ok this could be an approach but I'm not sure the url will always look like that. Could also be: de.wikipedia.org/wiki/BevölkerungsentwicklungResile
@Joerg: Sorry; I assumed the search term was user-input. :STitleholder
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.Mantinea
That method didn't exist when this question was answered, but that's now correct.Titleholder
A
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];
Attain answered 10/11, 2010 at 16:23 Comment(1)
hm yes but I'm looking more for a solution to encode any url. it also could be: de.wikipedia.org/wiki/BevölkerungsentwicklungResile
T
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);
}
Thegn answered 14/4, 2013 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.