skip to Main Content

So I’m a little confused. I have an NSURL like this

https://something/something/test#4.html

I want to remove the last path of this. I tried using URLByDeletingLastPathComponent method but then it results in this.

https://something/something/#4.html

I want the end result to be the following.

https://something/something

2

Answers


  1. First you have to remove the fragment. Then the last path using deletingLastPathComponent().

    var url = URL(string: "https://something/something/test#4.html")
    
    if let fragment = url?.fragment{
        url = URL(string: (url?.absoluteString.replacingOccurrences(of: "#(fragment)", with: ""))!)
        url = url?.deletingLastPathComponent()
    }
    
    print(url!)
    
    Login or Signup to reply.
  2. A smart way to remove the fragment is URLComponents

    let url = URL(string: "https://something/something/test#4.html")!
    
    if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
        urlComponents.fragment = nil
        let trimmedURL = urlComponents.url!.deletingLastPathComponent()
        print(trimmedURL)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search