Best Practice to Parse URL Query String in Swift
Learn the easy way to read URL parameters
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 🤭
http://www.example.com/landing/index?uid=L011403&token=clZAAWxBL1SP55qpR02FsDesY&success=1&souce=http://fb.com/swift&flag=4
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”
References
https://developer.apple.com/documentation/foundation/urlcomponents