_z6r2a
Last Updated: February 25, 2016
·
693
· adamyanalunas

Proper URL path escaping in Cocoa

Don't do this:

NSString *escaped = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Do this:

CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL,
                                                          (CFStringRef)path,
                                                          NULL,
                                                          CFSTR(";?#"),
                                                          kCFStringEncodingUTF8);

2 Responses
Add your response

8710
Meteor

Why?

over 1 year ago ·
8711

Because stringByAddingPercentEscapesUsingEncoding alone does not strictly conform to what can be escaped in arguments and you may end up with skipped, unencoded characters in your string. That would result in a malformed URL with incorrect parameters.

That would result in great sadness. And probably sadness as well.

over 1 year ago ·