Introduced in iOS 8 and OS X 10.10 is NSURLQueryItem
, which can be used to build queries. From the docs on NSURLQueryItem:
An NSURLQueryItem object represents a single name/value pair for an item in the query portion of a URL. You use query items with the queryItems property of an NSURLComponents object.
You can retrieve the query items from a URL by first creating NSURLComponents
:
NSURL *url = [NSURL URLWithString:@"http://stackoverflow.com?q=ios&count=10"];
NSURLComponents *components = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:YES];
for (NSURLQueryItem *item in components.queryItems) {
NSLog(@"name: %@, value: %@", item.name, item.value);
}
// name: q, value: ios
// name: count, value: 10
Note that they return value for -queryItems
is an array, not a dictionary. This is because the following is a valid URL. Note the two identical "keys", foo
.
http://google.com?foo=bar&foo=baz
To create a URL via query items, use the designated initializer queryItemWithName:value:
and then add them to NSURLComponents
to generate an NSURL
. For example:
NSString *urlString = @"http://stackoverflow.com";
NSURLComponents *components = [NSURLComponents componentsWithString:urlString];
NSURLQueryItem *search = [NSURLQueryItem queryItemWithName:@"q" value:@"ios"];
NSURLQueryItem *count = [NSURLQueryItem queryItemWithName:@"count" value:@"10"];
components.queryItems = @[ search, count ];
NSURL *url = components.URL; // http://stackoverflow.com?q=ios&count=10
Notice that the question mark and ampersand are automatically handled. Creating an NSURL
from a dictionary of parameters is as simple as:
NSDictionary *queryDictionary = @{ @"q": @"ios", @"count": @"10" };
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in queryDictionary) {
NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:key
value:queryDictionary[key]];
[queryItems addObject:item];
}
components.queryItems = queryItems;
I've also written a blog post with more details, Building NSURLs with NSURLQueryItems.