Reputation: 569
I have an URL that looks like myapp://jhb/test/deeplink/url?id=4567
.
I want to delete every thing after the ?
char. At the end the URL should look like myapp://jhb/test/deeplink/url
. how. can I achieve that? convert the url to a string? Regex?
Upvotes: 13
Views: 11668
Reputation: 31645
can I achieve that? convert the url to a string? Regex?
When working with URLs, it would be better to treat it as URLComponent
:
A structure that parses URLs into and constructs URLs from their constituent parts.
therefore, referring to URLComponent what are you asking is to remove the the query subcomponent from the url:
if var components = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567") {
components.query = nil
print(components) // myapp://jhb/test/deeplink/url
}
Note that query
is an optional string, which means it could be nil (as mentioned in the code snippet, which should leads to your desired output).
Upvotes: 4
Reputation: 48135
A convenient extension on URL
private extension URL {
var removingQueries: URL {
if var components = URLComponents(string: absoluteString) {
components.query = nil
return components.url ?? self
} else {
return self
}
}
}
Upvotes: 9
Reputation: 57154
Use URLComponents
to separate the different URL parts, manipulate them and then extract the new url:
var components = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567")!
components.query = nil
print(components.url!)
myapp://jhb/test/deeplink/url
Upvotes: 17
Reputation: 5428
You can get each URL component separated from URl using
print("\(url.host!)") //Domain name
print("\(url.path)") // Path
print("\(url.query)") // query string
Upvotes: 0
Reputation: 2455
You can do like this
let values = utl?.components(separatedBy: "?")[0]
It will break the string with ?
and return the array.
The first object of values
give you your resultant string.
Upvotes: 0