【问题标题】:Unable to construct URL from String containing multiple anchor in swift无法快速从包含多个锚点的字符串构造 URL
【发布时间】:2019-05-08 10:06:52
【问题描述】:

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

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

该 URL 有效,我们可以在浏览器中打开它。我的网址中的 # 并没有真正充当锚点,它实际上打开了一个新页面。 有没有办法在 url 路径中创建带有多个 # 的 URL?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    我发现这个小解决方法可能会解决您的问题

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

    【讨论】:

    【解决方案2】:

    有一个想法,将第二个、第三个等锚符号#替换为转义字符序列%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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-20
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2010-11-01
      相关资源
      最近更新 更多