0

I am trying to encode the special characters. It doesn't work for all. I am requesting URL which contains name and address. Before requesting i encode the URL but some special characters are not percent encoded.

NSString *encodedString = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

url = [[NSURL alloc ] initWithString:encodedString];

Thanks in advance.

VJVJ
  • 435
  • 3
  • 21

2 Answers2

0

try this one. I had similar issue and it helped:

- (NSString *) URLEncodedString {
    NSMutableString * output = [NSMutableString string];
    const char * source = [self UTF8String];
    int sourceLen = strlen(source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = (const unsigned char)source[i];
        if (false && thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}
Mobile Developer
  • 5,730
  • 1
  • 39
  • 45
0

The URL encoding issue with stringByAddingPercentEscapesUsingEncoding is already discussed of SO:

https://stackoverflow.com/a/8086845

In short, using stringByAddingPercentEscapesUsingEncoding is a bad idea unless you don't want to encode slashes and few other characters (which may be the case in some scenarios). Instead, you should use a CFURLCreateStringByAddingPercentEscapes function from Core Foundation. Check out the link above - it contains code examples and more detailed explanations.

Community
  • 1
  • 1
Andrew Simontsev
  • 1,078
  • 9
  • 18