Retrieving query parameters from URL in Swift
As developers, we often used to handle the url’s .
There are 2 ways how one can implement deep linking in IOS: URL scheme and Universal Links. URL schemes are a popular way of having deep linking, while Universal links are the new workaround how Apple has implemented to easily connect your webpage and your app under the same link.
I will not talk about how to implement the deep linking in mobile Application or how to handle it. In this I will show you how one can easily get the query param’s from any URL using Swift in Key-Value pair Dictionary.
What is key-value pair ?
A key-value pair (KVP) is a set of two linked data items: a key, which is a unique identifier for some item of data, and the value, which is either the data that is identified or a pointer to the location of that data.
How to get query param’s from URL in Swift ?
To get the query param’s in dictionary format from a URL string in swift we use ‘NSURLComponents’. NSURLComponents have a propery of ‘queryItems’ which is a array property contains array of query items in a valid URL.
Let see how it is used to the query parms:
First we have to convert our url string into concrete URL type :
let linkUrl = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed))
After converting into URL get the URLComponets using NSURLComponents.
let components:NSURLComponents? = NSURLComponents(url: linkUrl, resolvingAgainstBaseURL: true)
At last get the query items in from NSURLComponents. It will return the query items in [URLQueryItem] type.
let queryItems = components.queryItems
To get the query item in dictionary type we have to iterate through ‘queryItems’ array.
var queryItems: [String: String] = [:]
for item in queryItems {
queryItems[item.name] = item.value?.removingPercentEncoding
}
Below is the final code snippet.
Thanks for reading, hope this is helpful.