---
title: "#128: NSURLQueryItem \u0026 NSURLComponents 🌐"
url: https://littlebitesofcocoa.com/128-nsurlqueryitem-nsurlcomponents
author: Jake Marsh
date: 2015-11-18
published: 2015-11-18
topics: ["Networking","Foundation"]
description: "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."
---

# #128: NSURLQueryItem & NSURLComponents 🌐

By Jake Marsh, November 18, 2015. HTML: https://littlebitesofcocoa.com/128-nsurlqueryitem-nsurlcomponents

_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 <i>easily</i> 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**:

``` swift
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](https://www.ietf.org/rfc/rfc3986.txt) standard.

So far we've only created _components_ from scratch, but we could also get the _components_ of an <i>existing</i> NSURL like this:

``` swift
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 <i>*shudder*</i> 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](http://matthewbischoff.com/) for suggesting today's topic! Send <i>your</i> topic suggestion to [hello@littlebitesofcocoa.com](mailto:hello@littlebitesofcocoa.com)
