Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeswang-gist/3126753 to your computer and use it in GitHub Desktop.
Save jeswang-gist/3126753 to your computer and use it in GitHub Desktop.
Objective-C: url encoding
+(NSString*)stringByURLEncodingStringParameter:(NSString*)originalStr
{
// NSURL's stringByAddingPercentEscapesUsingEncoding: does not escape
// some characters that should be escaped in URL parameters, like / and ?;
// we'll use CFURL to force the encoding of those
//
// We'll explicitly leave spaces unescaped now, and replace them with +'s
//
// Reference: [url]http://www.ietf.org/rfc/rfc3986.txt[/url]
NSString *resultStr = nil;
CFStringRef originalString = (__bridge CFStringRef) originalStr;
CFStringRef leaveUnescaped = CFSTR(" ");
CFStringRef forceEscaped = CFSTR("!*'();:@&=+$,/?%#[]");
NSString *escapedStr;
escapedStr = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
originalString,
leaveUnescaped,
forceEscaped,
kCFStringEncodingUTF8));
if( escapedStr )
{
// replace spaces with plusses
resultStr = [escapedStr stringByReplacingOccurrencesOfString:@" "
withString:@"%20"];
}
return resultStr;
}
@callicoder
Copy link

Thanks for the gist. URLs can also be encoded online using URLEncoder.io tool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment