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?
Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.
To get the url parameter from a current route, we can use the useParams() hook in react router v5. Consider, we have a route like this in our react app. Now, we can access the :id param value from a Users component using the useParams() hook. In React router v4, you can access it using the props.match.params.id .
Given a URL and the task is to add an additional parameter (name & value) to the URL using JavaScript. URL. searchParams: This readonly property of the URL interface returns a URLSearchParams object providing access to the GET decoded query arguments in the URL.
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 } } }
Step 1: Create URL extension
extension URL { func valueOf(_ queryParameterName: String) -> String? { guard let url = URLComponents(string: self.absoluteString) else { return nil } return url.queryItems?.first(where: { $0.name == queryParameterName })?.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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With