an0
an0

Reputation: 17530

Why is # char before URL fragment encoded by stringByAddingPercentEscapesUsingEncoding?

Isn't # a legal character when used to specify fragment in URL?

Then why [@"http://google.com#abc" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] returns @"http://google.com%23abc" instead of @"http://google.com#abc"?

Upvotes: 0

Views: 195

Answers (1)

Rob
Rob

Reputation: 437622

The stringByAddingPercentEscapesUsingEncoding method cannot easily determine that the # in the string is a valid indication that the fragment will follow, or whether it was, for example, part of some query in which it should percent escape it:

http://google.com?q=#1

So, in your example, you wouldn't want it percent escaped, but in the above example (where you wanted to specify the value #1 for the parameter named q) you would.

I must agree, though, that it is curious that they percent escape # but not & or +.

For greater control over what characters are percent escaped and which are not, you may want to consider stringByAddingPercentEncodingWithAllowedCharacters or CFURLCreateStringByAddingPercentEscapes.

For example, if you wanted to apply the standard percent escaping logic, but leave the # characters unescaped, you could do:

NSString *escaped = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                              (CFStringRef)string,
                                                                              CFSTR("#"),
                                                                              NULL,
                                                                              kCFStringEncodingUTF8));

This obviously assumes that the # will never occur in the query before the fragment.

The more generalized solution would apply different percent-escaping logic to the various components of the URL (what's allowed as separators between the components are not allowed within the individual components).

Upvotes: 1

Related Questions