Created
July 17, 2012 03:06
-
-
Save jeswang-gist/3126753 to your computer and use it in GitHub Desktop.
Objective-C: url encoding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| +(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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the gist. URLs can also be encoded online using URLEncoder.io tool.