Fattie
Fattie

Reputation: 12592

How to get "everything after the ://" in iOS `URL`

Say you get a URL from iOS, perhaps

guard let incomingURL = userActivity.webpageURL else { .. }

I want "everything after the ://" as a string.

That is to say, everything except the scheme stuff up to and including the two slashes which follow the scheme.

Alert. Apparently "http:", not "http://", is the scheme.

unfortunately .path will give you something like /blah

I want blah/blob/blab+-&abc=+//cbvc/abc=+-%29k/doa

Other than just a munge,

how do you do this properly, likely using URL or perhaps URLComponents?


Footnote, per @MatthewKorporaal you can now just

var uc = URLComponents(url: u, resolvingAgainstBaseURL: true)!
uc.scheme = nil
uc.url?.absoluteString) is "//www. etc"

to strip precisely the "http:" part. (The // will remain.)

Upvotes: 0

Views: 1311

Answers (3)

Matthew Korporaal
Matthew Korporaal

Reputation: 2384

You can use URLComponents if you make it mutable.

var urlComponents = URLComponents(url: incomingURL, resolvingAgainstBaseURL: true)!
urlComponents.scheme = nil

Then, use the URL from the components.

print(urlComponents.url?.absoluteString)

www.example.com/blahblahblahblah/blob/blab+-&abc=+//cbvc/abc=+-%29k/doa

Update: As @Fattie said, it does not drop the "//" before, so you can add .replacingOccurrences(of: "//", with: "") to the absoluteString to get the path only.

urlComponents.url!.absoluteString.replacingOccurrences(of: "//", with: "")

Upvotes: 2

vadian
vadian

Reputation: 285069

Get the range of the host and create a substring starting with the host

guard let incomingURL = userActivity.webpageURL,
    let host = incomingURL.host,
    let range = incomingURL.absoluteString.range(of: host) {
    let urlMinusScheme = String(incomingURL.absoluteString[range.lowerBound...]) else { ...
print(urlMinusScheme) 

Or strip the scheme with Regular Expression

guard let incomingURL = userActivity.webpageURL else { ...
let urlMinusScheme = incomingURL.absoluteString.replacingOccurrences(of: "^https?://", with: "", options: .regularExpression)
print(urlMinusScheme)

Edit:

Another way is to strip the scheme from the absolute string

var urlMinusScheme = url.absoluteString
if let scheme = url.scheme {
    let startIndex =  urlMinusScheme.range(of: scheme + "://")!.upperBound
    urlMinusScheme = String(urlMinusScheme[startIndex...])
}

Upvotes: 1

koen
koen

Reputation: 5729

If you just want a string as the result, I would get the string from the url, split it in two at ://, and grab the second half.

Something like this:

let incomingURL = URL(string: "https://www.example.com/blahblahblahblah/blob/blab+-&abc=+//cbvc/abc=+-%29k/doa")

if let components = incomingURL?.absoluteString.components(separatedBy: "://") {
   let lastPart = components.last!
   print(lastPart)
}

This prints:

www.example.com/blahblahblahblah/blob/blab+-&abc=+//cbvc/abc=+-%29k/doa

Upvotes: -1

Related Questions