I'm trying to get the parameters from a URL using Swift. Let's say I have the following URL:
https://test.page.link/foo?accessCode=GA362078&bar=test
How can I get the value of foo?accessCode
(GA362078), and bar
(test)?
I'm trying to get the parameters from a URL using Swift. Let's say I have the following URL:
https://test.page.link/foo?accessCode=GA362078&bar=test
How can I get the value of foo?accessCode
(GA362078), and bar
(test)?
Use the queryItems
of URLComponents
:
func value(for name: String, in urlString: String, with path: String) -> String? {
if let components = URLComponents.init(string: urlString) {
if components.path == path {
return components.queryItems?.first { $0.name == name }?.value
}
else {
return("Not found")
}
}
return nil
}
let urlString = "https://test.page.link/foo?accessCode=GA362078&bar=test"
if let accessCodeValue = value(for: "accessCode", in: urlString, with: "/foo") {
print(accessCodeValue)
}
Output:
GA362078