× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Creating URL query parameters from NSDictionary objects in ObjectiveC

Joe Masilotti
May 13, 2015
<p>Introduced in iOS8 and OS X 10.10 is <code>NSURLQueryItem</code>, which can be used to build queries. From the docs on <a href="https://developer.apple.com/Library/ios/documentation/Foundation/Reference/NSURLQueryItem_Class/index.html">NSURLQueryItem</a>:</p> <blockquote> <p>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.</p> </blockquote> <p>To create one use the designated initializer <code>queryItemWithName:value:</code> and then add them to <code>NSURLComponents</code> to generate an <code>NSURL</code>. For example:</p> <pre><code>NSURLComponents *components = [NSURLComponents componentsWithString:@"http://stackoverflow.com"]; 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&amp;count=10 </code></pre> <p>Notice that the question mark and ampersand are automatically handled. Creating an <code>NSURL</code> from a dictionary of parameters is as simple as:</p> <pre><code>NSDictionary *queryDictionary = @{ @"q": @"ios", @"count": @"10" }; NSMutableArray *queryItems = [NSMutableArray array]; for (NSString *key in queryDictionary) { [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:queryDictionary[key]]]; } components.queryItems = queryItems; </code></pre> <p>Edit: I've also written a <a href="http://pivotallabs.com/nsurlqueryitems/">blog post</a> on how to build URLs with <code>NSURLComponents</code> and <code>NSURLQueryItems</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/718429/Creating%20URL%20query%20parameters%20from%20NSDictionary%20objects%20in%20ObjectiveC/26539134">Stack Overflow</a>.</p>
comments powered by Disqus