Using URLComponents in Swift 3

Janl Codes
3 min readNov 27, 2016

--

As developers, we often are faced with less-than-helpful documentation covering a specific concept in programming. So I’m going to try to bridge the gap between never setting your sights on the Apple Documentation covering NSURLComponents (renamed in Swift 3 as URLComponents) to a thorough understanding of when and how to use this fabulous semi-obscure struct.

The API asks for (in a very specific format): latitude, longitude, and date.

I could hand all this info to the API as a string and simply concatenate the parts making each element changeable upon each inquiry, demonstrated like so:

let url = api.openweathermap.org/data/2.5/weather?
let lat = "lat=35"
let lon = "&lon=139"
let now = "&2018-09-20"
let aggregatedURL = url + lat + lon + now

In the above example, we’re leaving us open to careless errors by assigning each piece separately. In a URL, if one character is off, consider it disaster to your user.

So rather than lead our user down a horrible user experience, let’s use the more seamless method of querying and assigning elements to our URL, by incorporating URLComponents.

Why URLComponents? According to Apple, it’s “designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.” In essence, it creates a structure with which to build a URL. URLComponents offers a promising protective measure: it error checks before trying to enter a constituent part that would normally not fit into the URL segment or component (i.e. scheme, host, port, etc.)

Apple Docs asks that we use the following format for queryItems. We’ll need to create an array of queryItem objects despite the number of components we’re actually going to employ. In our case, we simply need two (2) queryItems, the latitude and longitude.

Instance Property — var queryItems

Next, we’ll need to conform to the key-value construct to create each queryItem. Regarding each queryItem object, the Apple Docs state each “represents a single key-value pair, in the order in which they appear in the original query string”.

In our case, we simply need two (2), the latitude and longitude.

let latQueryItem = URLQueryItem(name: "lat", value: "\(location.coordinate.latitude)")

“When you set this property’s value, the NSURLComponents class joins each name/value pair with a =delimiter and joins the array with a & delimiter, then sets the query property to the resulting string.”

Ok! Apple gives you delimiters for free! One less thing to worry about.

So let’s construct a URL from scratch to better demonstrate how the struct works.

Our newURLComponents Object

In the above, we were able to create a new component object using the pre-packed properties that come with this struct. I tested the above in a playground and as you can see it builds each portion of the URL as it receives more components.

However, notice what happens when we leave out a seemingly innocuous character like a forward slash (“/”) in our path.

Without the complete path (“/playlist”), the playground will only show the separate components. Probably best to keep the forward slash in the string.

So as you can see, URLComponents is flat out better than string concatenation when composing a URL in Swift because the components can only be modified in very specific ways, it’s easier to view and catch errors (and the compiler will offer you help), plus it forces you to be specific about defining each piece.

Hope this was a painless introduction! Enjoy!

--

--