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?
I've got another solution:
http://splinter.com.au/build-a-url-query-string-in-obj-c-from-a-dict
You can then use it like so:
You can create a category for
NSDictionary
to do this -- there isn't a standard way in the Cocoa library that I could find either. The code that I use looks like this:with this implementation:
I think the code's pretty straightforward, but I discuss it in some more detail at http://blog.ablepear.com/2008/12/urlencoding-category-for-nsdictionary.html.
I took Joel's recommendation of using
URLQueryItems
and turned into a Swift Extension (Swift 3)(The
self.init
method is kinda cheesy, but there was noNSURL
init with components)Can be used as
I wanted to use Chris's answer, but it wasn't written for Automatic Reference Counting (ARC) so I updated it. I thought I'd paste my solution in case anyone else has this same issue. Note: replace
self
with the instance or class name where appropriate.Here is a simple example in Swift (iOS8+):