Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Creating a query string from an NSDictionary.

View NSDictionary+QueryStringBuilder.h
1 2 3 4 5 6 7 8
#import <Foundation/Foundation.h>
 
 
@interface NSDictionary (QueryStringBuilder)
 
- (NSString *)queryString;
 
@end
View NSDictionary+QueryStringBuilder.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#import "NSDictionary+QueryStringBuilder.h"
 
 
@implementation NSDictionary (QueryStringBuilder)
 
- (NSString *)queryString
{
NSMutableString *queryString = nil;
NSArray *keys = [self allKeys];
if ([keys count] > 0) {
for (id key in keys) {
id value = [self objectForKey:key];
if (nil == queryString) {
queryString = [[[NSMutableString alloc] init] autorelease];
[queryString appendFormat:@"?"];
} else {
[queryString appendFormat:@"&"];
}
if (nil != key && nil != value) {
[queryString appendFormat:@"%@=%@", key, value];
} else if (nil != key) {
[queryString appendFormat:@"%@", key];
}
}
}
return queryString;
}
 
@end
View NSDictionary+QueryStringBuilder.h
1 2
NSDictionary *queryParameters = [NSDictionary dictionaryWithValuesAndKeys:1, @"page", nil, @"enabled", 25, @"size", nil];
[queryParameters queryString]; // This will return "?page=1&enabled&size=25"

The argument name for escapeString() should be unencodedString instead of string, as this is the name used on the CFURLCreateStringByAddingPercentEscapes call. My fork of this gist fixes this so the code compiles.

It also makes escapeString() a static function to avoid compiler warnings.

Owner

Thanks for the spots :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.