TIL: URLComponents, URLQueryItem, and URLRequest

Table of Content

TIL

I always love learning new stuff! Well, at least when it’s new stuff I care about.

Today I learned that there’s a better way to construct queries for apis or fetching web data. A Swifty new feature (new compared to Objective C at least) called URLComponents, along with their counterpart URLQueryItem (disclaimer, there may be many more counterparts, but these are the ones I just learned about).

My ways of yore AKA the wrong way

Previously, if I wanted to fetch api data or, more simply write an app that just opens a query in YouTube search, I would something similar do the following:

  1. Analyze a URL after having done a test search:
    • https://www.youtube.com/results?search_query=test+search
  2. Separate the string into separate, usable components:
    • ex:
      • https://www.youtube.com/results?
      • search_query=
      • test+search (not needed since that’s the variable data)
  3. Then when the user provides input, I’d run the user input string through sanitization and URL encoding conversion and just combine strings:
    • https://www.youtube.com/results? + search_query= + sanitizeAndEncode(userInput)
  4. Finally I’d initialize a URL using this string and pass it into URLSession.shared.dataTask

The RIGHT Way

  1. I still might analyze a URL, but we covered researching API documentation as well, so that’s beneficial as well.
    • let baseURL = URL(string: "https://www.youtube.com/results")!
  2. Create a URLComponents variable (It’s a struct, so we need to make it a var to edit it!):
    • var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
  3. Create a URLQueryItem:
    • let query = URLQueryItem(name: "search_query", value: "test search")
  4. Add your query(ies) to the components:
    • components?.queryItems = [query]
  5. Use the url property however you choose!
    • components?.url
    • it takes care of sanitization and encoding for you
    • it handles all of the syntax to go with a URL automatically

Part 2: The second part

I also learned about URLRequest.

When you run URLSession.shared.dataTask, it gives you the option of using a URL or a URLRequest. It seemed a bit silly to me since a URLRequest is literally inited by passing in a URL, but the reason is that a URLRequest then has the option of changing whether you want a GET, POST, DELETE, or whatever HTTP Method you would like, as well as providing a way to modify header data.

That’s pretty cool.

Leave a Reply

Your email address will not be published. Required fields are marked *