Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.

NSURLQueryItem is a great little class that joined Foundation in iOS 8. It can help us compose NSURLs in a safer and more predictable way.

iOS and OS X developers have long become familiar with composing URLs in Cocoa. It can be… "interesting" at times.

We've all written a line or two of NSString-concatenation or stringWithFormat code to quickly create a URL. This works in a pinch, but we could easily introduce a bug by putting an & character in the wrong spot, or some other silly typo.

NSURLQueryItem can help! Let's look at how to use it along with NSURLComponents to compose an NSURL:

let components = NSURLComponents()

components.scheme = "https"
components.host = "api.spaceshipapp.com"
components.path = "/ships"

components.queryItems = [
  NSURLQueryItem(name: "start", value: "40"),
  NSURLQueryItem(name: "max_results", value: "20")

let requestURL = components.URL

NSURLComponents is quite a useful class on its own that can parse and assemble URLs based on the RFC 3986 standard.

So far we've only created components from scratch, but we could also get the components of an existing NSURL like this:

let components = NSURLComponents(
  URL: NSURL(string: "https://lboc.me?page=2")!,
  resolvingAgainstBaseURL: true

This is great for a few reasons. For example, instead of doing something silly like string replacing shudder to change a query parameter, we can instead operate on the components' queryItems array, then export the URL again by calling .URL. Additionally, with this technique, we can now more easily validate query parameters in URLs in our tests! Double-win. Neat!

Thanks to Matthew Bischoff for suggesting today's topic! Send your topic suggestion to hello@littlebitesofcocoa.com