With all the URL-handling objects lying around in the standard Cocoa libraries (NSURL, NSMutableURL, NSMutableURLRequest, etc), I know I must be overlooking an easy way to programmatically compose a GET request.
Currently I'm manually appending "?" followed by name value pairs joined by "&", but all of my name and value pairs need to be manually encoded so NSMutableURLRequest doesn't fail entirely when it tries to connect to the URL.
This feels like something I should be able to use a pre-baked API for…. is there anything out of the box to append an NSDictionary of query parameters to an NSURL? Is there another way I should approach this?
Best Answer
Introduced in iOS8 and OS X 10.10 is
NSURLQueryItem
, which can be used to build queries. From the docs on NSURLQueryItem:To create one use the designated initializer
queryItemWithName:value:
and then add them toNSURLComponents
to generate anNSURL
. For example:Notice that the question mark and ampersand are automatically handled. Creating an
NSURL
from a dictionary of parameters is as simple as:I've also written a blog post on how to build URLs with
NSURLComponents
andNSURLQueryItems
.