Created
March 8, 2016 15:45
-
-
Save ghthor/300171f0df0d4b4eeaaa to your computer and use it in GitHub Desktop.
ObjC URL Query String builder
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
| // | |
| // 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 |
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
| // | |
| // 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