iosswift

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.)


Solution

  • 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...])
    }