Skip to content

Instantly share code, notes, and snippets.

@dnpp73
Created November 10, 2012 09:57
Show Gist options
  • Save dnpp73/4050594 to your computer and use it in GitHub Desktop.
Save dnpp73/4050594 to your computer and use it in GitHub Desktop.
Query String with Hash (Objective-C + ARC)
@interface NSArray (flatten)
- (NSArray *)flatten;
@end
@implementation NSArray (flatten)
- (NSArray *)flatten
{
__block NSMutableArray *copiedArray = [NSMutableArray array];
__block void (^f)(NSArray *array) = ^(NSArray *array) {
for (id obj in array) {
if ([obj isKindOfClass:[NSArray class]]) {
f(obj);
} else {
[copiedArray addObject:obj];
}
}
};
f(self);
return [copiedArray copy];
}
@end
@interface NSURL (queryStrings)
- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)parameters;
+ (NSString *)queryStringWithParameters:(NSDictionary *)parameters;
@end
@implementation NSURL (queryStrings)
- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)parameters
{
if (parameters == nil) {
return self;
}
NSString *string = self.absoluteString;
NSString *queryString = [self.class queryStringWithParameters:parameters];
NSString *delimiter = nil;
if ([string rangeOfString:@"?"].length == 0) {
delimiter = @"?";
} else {
delimiter = @"&";
}
NSString *URLString = [NSString stringWithFormat:@"%@%@%@", self.absoluteString, delimiter, queryString];
return [NSURL URLWithString:URLString];
}
+ (NSArray *)queryStringsWithKey:(NSString *)key value:(id)value
{
__block NSMutableArray *queries = [NSMutableArray array];
if ([value isKindOfClass:[NSArray class]]) {
[(NSArray *)value enumerateObjectsUsingBlock:^(id innerValue, NSUInteger idx, BOOL *stop) {
id query = [self queryStringsWithKey:[NSString stringWithFormat:@"%@[]", key]
value:innerValue];
[queries addObject:query];
}];
} else if([value isKindOfClass:[NSDictionary class]]) {
[(NSDictionary *)value enumerateKeysAndObjectsUsingBlock:^(id innerKey, id innerValue, BOOL *stop) {
id query = [self queryStringsWithKey:[NSString stringWithFormat:@"%@[%@]", key, innerKey]
value:innerValue];
[queries addObject:query];
}];
} else {
[queries addObject:[NSString stringWithFormat:@"%@=%@", key, value]];
}
return [queries flatten];
}
+ (NSString *)queryStringWithParameters:(NSDictionary *)parameters
{
NSMutableArray *queryStrings = [NSMutableArray array];
for (NSString *key in parameters.allKeys) {
id value = [parameters objectForKey:key];
[queryStrings addObject:[self queryStringsWithKey:key value:value]];
}
return [[queryStrings flatten] componentsJoinedByString:@"&"];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment