Get the value of URL Parameters
I am trying to get the parameters from a URL using Swift. Let's say I have the following URL:
http://mysite3994.com?test1=blah&test2=blahblah
How can I get the values of test1 and test2?
Solution 1:
You can use the belowCode to get the param
func getQueryStringParameter(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}
Call the method like let test1 = getQueryStringParameter(url, param: "test1")
Other method with extension:
extension URL {
public var queryParameters: [String: String]? {
guard
let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}
Solution 2:
Step 1: Create URL extension
extension URL {
func valueOf(_ queryParamaterName: String) -> String? {
guard let url = URLComponents(string: self.absoluteString) else { return nil }
return url.queryItems?.first(where: { $0.name == queryParamaterName })?.value
}
}
Step 2: How to use the extension
let newURL = URL(string: "http://mysite3994.com?test1=blah&test2=blahblah")!
newURL.valueOf("test1") // Output i.e "blah"
newURL.valueOf("test2") // Output i.e "blahblah"
Solution 3:
I also made a URL extension, but put the query param lookup into a subscript.
extension URL {
subscript(queryParam:String) -> String? {
guard let url = URLComponents(string: self.absoluteString) else { return nil }
return url.queryItems?.first(where: { $0.name == queryParam })?.value
}
}
Usage:
let url = URL(string: "http://some-website.com/documents/127/?referrer=147&mode=open")!
let referrer = url["referrer"] // "147"
let mode = url["mode"] // "open"