Created
December 13, 2012 21:11
-
-
Save Gi-lo/4279932 to your computer and use it in GitHub Desktop.
Easily create GET NSURLs in Objective-C. (Used in https://github.com/Gi-lo/GCXHTTPOperation )
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
- (NSURL *)URLWithString:(NSString *)string andQueryValuesForKeys:(NSString *)value, ... { | |
if (!value) { | |
return [NSURL URLWithString:string]; | |
} | |
NSMutableString *queryString = [NSMutableString string]; | |
NSString *argument = nil; | |
NSUInteger argumentCount = 0; | |
va_list argumentList; | |
va_start(argumentList, value); | |
while ((argument = va_arg(argumentList, NSString *))) { | |
argumentCount++; | |
if (argumentCount % 2 == 0) { | |
value = [argument serializedString]; | |
} else { | |
NSString *separator = @"&"; | |
if (argumentCount == 1) { | |
separator = @"?"; | |
} | |
[queryString appendFormat:@"%@%@=%@", separator, argument, [value serializedString]]; | |
} | |
} | |
va_end(argumentList); | |
NSAssert(argumentCount % 2 != 0, @"Uneven amount of query keys and values."); | |
return [NSURL URLWithString:[string stringByAppendingString:queryString]]; | |
} | |
Example usage: | |
NSURL *url = [self URLWithString:@"http://search.twitter.com/search.json" andQueryValuesForKeys:term, @"q", @"100", @"rpp", nil]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment