Created
April 13, 2011 02:17
-
-
Save chrishulbert/916845 to your computer and use it in GitHub Desktop.
Build a url query string in obj-c from a dictionary of params like jquery does
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*)urlEscape:(NSString *)unencodedString { | |
NSString *s = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, | |
(CFStringRef)unencodedString, | |
NULL, | |
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", | |
kCFStringEncodingUTF8); | |
return [s autorelease]; // Due to the 'create rule' we own the above and must autorelease it | |
} | |
// Put a query string onto the end of a url | |
+(NSString*)addQueryStringToUrl:(NSString *)url params:(NSDictionary *)params { | |
NSMutableString *urlWithQuerystring = [[[NSMutableString alloc] initWithString:url] autorelease]; | |
// Convert the params into a query string | |
if (params) { | |
for(id key in params) { | |
NSString *sKey = [key description]; | |
NSString *sVal = [[params objectForKey:key] description]; | |
// Do we need to add ?k=v or &k=v ? | |
if ([urlWithQuerystring rangeOfString:@"?"].location==NSNotFound) { | |
[urlWithQuerystring appendFormat:@"?%@=%@", [Http urlEscape:sKey], [Http urlEscape:sVal]]; | |
} else { | |
[urlWithQuerystring appendFormat:@"&%@=%@", [Http urlEscape:sKey], [Http urlEscape:sVal]]; | |
} | |
} | |
} | |
return urlWithQuerystring; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment