I have a URL with a number of path components. Is there an elegant way to remove all path components? Basically, I just want to keep the scheme and the host of the URL. And the port, if available.
I can of course create a new URL object, using the relevant properties from the existing URL:
let newURL = "\(existingURL.scheme!)://\(existingURL.host!)"
Or loop over the pathcomponents, removing the last component, until none remains.
But both of these solutions doesn't seem that elegant, so I'm looking for a better, safer and more efficient solution.
The only possibility I see is to use URLComponents
and manually remove some components:
let url = URL(string: "http://www.google.com/and/my/path")!
print(url)
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
components.path = ""
print(components.url!) // http://www.google.com
If you decide to build URL manually, it's probably still better to use URLComponents
for that:
let url = URL(string: "http://www.google.com/and/my/path")!
var components = URLComponents()
components.scheme = url.scheme
components.host = url.host
print(components.url!) // http://www.google.com
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