1

I have received a URL string with double anchors, but I am unable to generate a URL object from that string.

let url = URL(string: "https://www.example.com/help.html#details#moredetails") // returns nil

The URL is valid and we are able to open it in browser. The # in my url does not really act as an anchor, it actually opens a new page. Is there any way to create URL with multiple # in the url path?

Vishal Singh
  • 4,400
  • 4
  • 27
  • 43

2 Answers2

0

I found this little workaround that might solve your problem

let htmlFilePath = "https://www.example.com/help.html"
var url = URL(string: htmlFilePath)
url = URL(string: "#details", relativeTo: url)!
url = URL(string: "#moredetails", relativeTo: url)!
Bartosz Kunat
  • 1,485
  • 1
  • 23
  • 23
  • 1
    I tried this, its finally converting to "https://www.example.com/help.html#moredetails" – Vishal Singh May 08 '19 at 10:39
  • My bad. I don't know if you've came across this post https://stackoverflow.com/questions/38658649/double-hashtag-in-openurl-crashes-the-app but it looks like this might be the cause why you can't initialize your URL – Bartosz Kunat May 08 '19 at 10:56
0

There is an idea to replace the second, third, and so on anchor symbols # with an escaped character sequence %23:

let stringUrl = "https://www.example.com/help.html#details#moredetails"
        
let hostWithAnchors = stringUrl.components(separatedBy: "#")
if hostWithAnchors.count > 2 {
    let hostWithPath = hostWithAnchors[0]
    let anchors = hostWithAnchors[1..<hostWithAnchors.count]
    let urlWithSeveralAnchors = hostWithPath + "#" + anchors.joined(separator: "%23")
            
    let url = URL(string: urlWithSeveralAnchors)
    // Continue working with the url
}
Rinat Abidullin
  • 141
  • 4
  • 4