Skip to content

Instantly share code, notes, and snippets.

@0xced
Last active December 20, 2018 10:54
Show Gist options
  • Save 0xced/1893145 to your computer and use it in GitHub Desktop.
Save 0xced/1893145 to your computer and use it in GitHub Desktop.
How to (ab)use TWRequest to create a NSURL with parameters easily
{
NSURL *baseURL = [NSURL URLWithString:@"http://duckduckgo.com/"];
NSDictionary *parameters = @{ @"q" : @"TWRequest -site:apple.com" };
// With TWRequest: 1 line with **correct percent escaping**
NSURL *urlA = [[[[TWRequest alloc] initWithURL:baseURL parameters:parameters requestMethod:TWRequestMethodGET] signedURLRequest] URL];
// Without TWRequest: 10 lines with wrong percent escaping (http://www.openradar.me/6546984)
NSMutableString *query = [NSMutableString string];
for (NSString *key in parameters)
{
if ([query length] > 0)
[query appendString:@"&"];
NSString *escapedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *escapedValue = [[parameters objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[query appendFormat:@"%@=%@", escapedKey, escapedValue];
}
NSURL *urlB = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", [baseURL absoluteString], query]];
NSLog(@"urlA = %@", urlA);
NSLog(@"urlB = %@", urlB);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment