Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all pathcomponents from a URL in Swift

Tags:

url

ios

swift

nsurl

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.

like image 991
rodskagg Avatar asked Dec 05 '22 11:12

rodskagg


1 Answers

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
like image 127
Sulthan Avatar answered Jan 02 '23 08:01

Sulthan