I've tried the following code in order to extract param value out of an existing url address
func getQueryStringParameter(url: String, param: String) -> String? {
guard let urlItems = URLComponents(string: url) else { return nil }
return urlItems.queryItems?.first(where: { $0.name == param })?.value
}
I called this method with the following input :
url = myprefix:un%3Dtest%26add=%3D1%26token%3Dbbbbbbbb
param = token
and I'd expect that the function to return token's value 'bbbbbbbb'
however, although the url is being parsed properly (here's printout from the debugger), the queryItems returns nil
po URLComponents(string: "myprefix:un%3Dtest%26add=%3D1%26token%3Dbbbbbbbb")
▿ Optional<URLComponents>
▿ some : myprefix:un%3Dtest%26add=%3D1%26token%3Dbbbbbbbb
- scheme : "myprefix"
- path : "un=test&add==1&token=bbbbbbbb"
How can I modify the function so that queryItems will be valid and I may extract the values out of path
properly ?
EDIT: after changing the ':' to '?' it looks like the query still isn't parsed properly because the UTF-8
formatting of the url, is there any way to convert it to the ascii representation automatically?
ascii :
(lldb) po URLComponents(string: "myprefix?un=test&add=1&token=bbbbbbbb")?.queryItems
▿ Optional<Array<URLQueryItem>>
▿ some : 3 elements
▿ 0 : un=test
- name : "un"
▿ value : Optional<String>
- some : "test"
▿ 1 : add=1
- name : "add"
▿ value : Optional<String>
- some : "1"
▿ 2 : token=bbbbbbbb
- name : "token"
▿ value : Optional<String>
- some : "bbbbbbbb"
UTF-8 :
(lldb) po URLComponents(string: "myprefix?un%3Dtest%26add=%3D1%26token%3Dbbbbbbbb")?.queryItems?.first
▿ Optional<URLQueryItem>
▿ some : un=test&add==1&token=bbbbbbbb
- name : "un=test&add"
▿ value : Optional<String>
- some : "=1&token=bbbbbbbb"
thanks