Skip to content

Instantly share code, notes, and snippets.

@ghthor
Created March 8, 2016 15:45
Show Gist options
  • Select an option

  • Save ghthor/300171f0df0d4b4eeaaa to your computer and use it in GitHub Desktop.

Select an option

Save ghthor/300171f0df0d4b4eeaaa to your computer and use it in GitHub Desktop.
ObjC URL Query String builder
//
// NSURLComponents+URLQueryEncoding.h
//
// Created by Willa Drengwitz on 3/8/16.
// Copyright © 2016 Willa Drengwitz. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSURLComponents (URLQueryEncoding)
// TODO: Turn into a computer property to enable 2way street
- (void) queryDictionary:(nullable NSDictionary *)parameters;
@end
//
// NSURLComponents+URLQueryEncoding.h
//
// Created by Willa Drengwitz on 3/8/16.
// Copyright © 2016 Willa Drengwitz. All rights reserved.
//
#import "NSURLComponents+URLQueryEncoding.h"
static NSString *__nonnull urlEncode(NSString *__nonnull string) {
return [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}
// TODO: Upgrade to support NSURLQueryItem(iOS 8.0)
static NSString *__nonnull queryStringFrom(NSDictionary *__nullable parameters) {
if (parameters == nil) {
return @"";
}
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:[parameters count]];
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
NSString *pair = [NSString stringWithFormat:@"%@=%@", urlEncode(key), urlEncode([obj stringValue])];
[pairs addObject:pair];
}];
return [pairs componentsJoinedByString:@"&"];
}
@implementation NSURLComponents (URLQueryEncoding)
- (void) queryDictionary:(nullable NSDictionary *)parameters {
self.query = queryStringFrom(parameters);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment