my question is pretty straight forward. Can someone please show me how to get the query string parameters in a url received by the UIWebView. It is pretty easy in objective c, but I need some help in swift as i'm new to the language. Thanks in advance.
3 Answers
In the NSURL class exists the .query property which returns the string of everything after the ? in the url in form:
http://www.example.com/index.php?key1=value1&key2=value2
in this example using the code:
var url: NSURL = NSURL(string: "http://www.example.com/index.php?key1=value1&key2=value2")
println(url.query) // Prints: Optional("key1=value1&key2=value2")
More information in the documentation
As far as getting the url from the uiwebview, you could use something along the lines of:
let url: NSURL = someWebView.NSURLRequest.URL
To make it a bit easier to get the value of a particular parameter you expect, you can use URLComponents which will parse out the query string parameters for you.
For example, if we want the value of the query string parameter key2 in this URL:
"https://www.example.com/path/to/resource?key1=value1&key2=value2"
We can create a URLComponents struct, then filter for the query item which matches the name, take the first one, and print its value:
let url = URL(string: "https://www.example.com/path/to/resource?key1=value1&key2=value2")
if let url = url,
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let parameterWeWant = urlComponents.queryItems?.filter({ $0.name == "key2" }).first
print(parameterWeWant?.value ?? "")
}
The key (!) thing is that urlComponents.queryItems gives us this array of QueryItem structs back, which gives us an easier way to filter the parameters and get the value of the parameter we're looking for.
▿ Optional([key1=value1, key2=value2])
▿ some: 2 elements
▿ key1=value1
- name: "key1"
▿ value: Optional("value1")
- some: "value1"
▿ key2=value2
- name: "key2"
▿ value: Optional("value2")
- some: "value2"
Comments
We can parse the Url params with this method,
func getParameterFrom(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}
let url = "http://www.example.com/index.php?key1=value1&key2=value2"
let key1 = self.getParameterFrom(url: url, param: "key1")
print("\(key1)") // value1