无法从包含多个锚的字符串中快速构造URL

时间:2019-05-08 10:06:52

标签: ios swift

我收到了带有双锚的URL字符串,但是无法从该字符串生成URL对象。

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

URL有效,我们可以在浏览器中打开它。我的网址中的#并不是真正的锚,它实际上会打开一个新页面。 有什么方法可以在URL路径中创建带有多个#的URL?

2 个答案:

答案 0 :(得分:0)

我发现了这种解决方法,可以解决您的问题

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

答案 1 :(得分:0)

有一个想法,用转义的字符序列#替换锚定符号%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
}