Best Practice to Parse URL Query String in Swift

Recently, I have been working on QR Code Scanning project which requires to read the scanned result (URL) and pulling out specific values in query string such as id, flag, success status, etc. Developer sometimes will parse it manually using few String methods and forget about the useful URLComponents.

URLComponents is the best tool to parse and construct url. It has been there since iOS7. Let’s do some practice.

1. Getting Value of Specific Query

Take a look at this string url example. Don’t click, it just an example 🤭

First, let’s try to find the value of parameter “success”. See the code below with the explanation in the comment of each lines.

In the code above, .queryItems is used to find all the queries inside the url and we try to find the value based on given key in .first(where: ..) closure.

Actually, this can be simplified in one line by using the Optional Chaining. That’s super cool!

2. Getting URL Path

It’s quite similar as before, except now we are looking at .path property rather than the .queryItems.

Great. Now, we already understand how to parse the url query strings in a proper way. You may try this in Xcode playground to understand the details. Happy coding!

Thanks for reading and don’t forget to share with you friends. Feedbacks are most welcome.

“Learn, that’s how we grow our skills”


iOS Developer focusing on Swift — “Learn, that’s how we grow our skill”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store